home *** CD-ROM | disk | FTP | other *** search
/ SPACE 2 / SPACE - Library 2 - Volume 1.iso / program / 318 / utilsrc / make.c < prev    next >
Encoding:
Text File  |  1988-10-20  |  191.3 KB  |  7,242 lines

  1. /* `make' - recompile files as needed.
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.    written by Richard Stallman and Roland McGrath.
  4.  
  5.                NO WARRANTY
  6.  
  7.   BECAUSE GNU MAKE IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  8. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  9. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  10. RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE GNU MAKE "AS IS"
  11. WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  12. BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  14. AND PERFORMANCE OF GNU MAKE IS WITH YOU.  SHOULD GNU MAKE PROVE
  15. DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  16. CORRECTION.
  17.  
  18.  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  19. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  20. WHO MAY MODIFY AND REDISTRIBUTE GNU MAKE AS PERMITTED BELOW, BE
  21. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  22. OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  23. USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  24. DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  25. A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) GNU MAKE,
  26. EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  27. DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  28.  
  29.         GENERAL PUBLIC LICENSE TO COPY
  30.  
  31.   1. You may copy and distribute verbatim copies of GNU Make source
  32. code as you receive it, in any medium, provided that you conspicuously
  33. and appropriately publish on each copy a valid copyright notice
  34. "Copyright (C) 1988 Free Software Foundation, Inc." (or with whatever
  35. year is appropriate), and include following the copyright notice a
  36. verbatim copy of the above disclaimer of warranty and of this License.
  37. You may charge a distribution fee for the physical act of transferring
  38. a copy.
  39.  
  40.   2. You may modify your copy or copies of GNU Make or
  41. any portion of it, and copy and distribute such modifications under
  42. the terms of Paragraph 1 above, provided that you also do the following:
  43.  
  44.     a) cause the modified files to carry prominent notices stating
  45.     that you changed the files and the date of any change; and
  46.  
  47.     b) cause the whole of any work that you distribute or publish,
  48.     that in whole or in part contains or is a derivative of GNU Make
  49.     or any part thereof, to be licensed at no charge to all
  50.     third parties on terms identical to those contained in this
  51.     License Agreement (except that you may choose to grant more extensive
  52.     warranty protection to some or all third parties, at your option).
  53.  
  54.     c) You may charge a distribution fee for the physical act of
  55.     transferring a copy, and you may at your option offer warranty
  56.     protection in exchange for a fee.
  57.  
  58. Mere aggregation of another unrelated program with this program (or its
  59. derivative) on a volume of a storage or distribution medium does not bring
  60. the other program under the scope of these terms.
  61.  
  62.   3. You may copy and distribute GNU Make (or a portion or derivative
  63. of it, under Paragraph 2) in object code or executable form under the terms
  64. of Paragraphs 1 and 2 above provided that you also do one of the following:
  65.  
  66.     a) accompany it with the complete corresponding machine-readable
  67.     source code, which must be distributed under the terms of
  68.     Paragraphs 1 and 2 above; or,
  69.  
  70.     b) accompany it with a written offer, valid for at least three
  71.     years, to give any third party free (except for a nominal
  72.     shipping charge) a complete machine-readable copy of the
  73.     corresponding source code, to be distributed under the terms of
  74.     Paragraphs 1 and 2 above; or,
  75.  
  76.     c) accompany it with the information you received as to where the
  77.     corresponding source code may be obtained.  (This alternative is
  78.     allowed only for noncommercial distribution and only if you
  79.     received the program in object code or executable form alone.)
  80.  
  81. For an executable file, complete source code means all the source code for
  82. all modules it contains; but, as a special exception, it need not include
  83. source code for modules which are standard libraries that accompany the
  84. operating system on which the executable file runs.
  85.  
  86.   4. You may not copy, sublicense, distribute or transfer GNU Make
  87. except as expressly provided under this License Agreement.  Any attempt
  88. otherwise to copy, sublicense, distribute or transfer GNU Make is void and
  89. your rights to use the program under this License agreement shall be
  90. automatically terminated.  However, parties who have received computer
  91. software programs from you with this License Agreement will not have
  92. their licenses terminated so long as such parties remain in full compliance.
  93.  
  94.   5. If you wish to incorporate parts of GNU Make into other free
  95. programs whose distribution conditions are different, write to the Free
  96. Software Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  97. worked out a simple rule that can be stated here, but we will often permit
  98. this.  We will be guided by the two goals of preserving the free status of
  99. all derivatives of our free software and of promoting the sharing and reuse of
  100. software.
  101.  
  102.  In other words, you are welcome to use, share and improve this program.
  103.  You are forbidden to forbid anyone else to use, share and improve
  104.  what you give them.   Help stamp out software-hoarding!  */
  105.  
  106. #if 0    /* dummy tags for etags */
  107. endcopyr (){}
  108. endcopyright (){}
  109. endlicense (){}
  110. #endif
  111.  
  112. #if 0    /* dummy tags for etags */
  113. rcs (){}
  114. log (){}
  115. #endif
  116.  
  117. /*
  118.  * $Header: make.c,v 2.0 88/06/28 21:57:40 mcgrath Rel $
  119.  *
  120.  $Log:    make.c,v $
  121.  * Revision 2.0  88/06/28  21:57:40  mcgrath
  122.  * Second release.
  123.  * 
  124.  * Revision 1.66  88/06/19  16:34:15  mcgrath
  125.  * Made it continue after ignored errors.
  126.  * 
  127.  * Revision 1.65  88/06/19  15:36:13  mcgrath
  128.  * Added variable references inside variable references.
  129.  * E.g.: $($(x)) ==> $(y) when x = y.  They are recursive so that
  130.  * if x = $(y) and y = z (notice recursive variable definitions),
  131.  * then $($(x)) goes -> $($(y)) -> $(z) -> value of z.
  132.  * 
  133.  * Revision 1.64  88/06/18  21:21:11  mcgrath
  134.  * Fixed an error message.
  135.  * 
  136.  * Revision 1.63  88/06/18  13:59:47  mcgrath
  137.  * Made error messages use the name of invokation instead
  138.  * of always using `make'.
  139.  * 
  140.  * Revision 1.62  88/06/18  13:35:05  mcgrath
  141.  * * Fixed up some error messages.
  142.  * * Made it say "*** Error n (ignored)" rather than nothing under -i.
  143.  * * Put run_shell_command inside execute_command_line.
  144.  * 
  145.  * Revision 1.61  88/06/17  20:59:49  mcgrath
  146.  * * Removed Bourne shell $(a-b), etc. variable reference constructs.
  147.  * * It is not longer a fatal error if Make doesn't know how to make
  148.  *   a file when -k is in effect.
  149.  * 
  150.  * Revision 1.60  88/06/15  01:33:29  mcgrath
  151.  * Made `foreach' control variables always be nonrecursive.
  152.  * They are restored to whatever recursiveness and value they
  153.  * had before the `foreach' call when it is done.
  154.  * 
  155.  * Revision 1.59  88/06/14  21:33:18  mcgrath
  156.  * Moved .s to the end of the default suffix list.
  157.  * 
  158.  * Revision 1.59  88/06/12  03:00:00  rms
  159.  * Move .s to end of default suffix list.
  160.  *
  161.  * Revision 1.58  88/06/10  11:01:41  mcgrath
  162.  * Removed an unused variable.
  163.  * 
  164.  * Revision 1.57  88/06/09  21:31:13  mcgrath
  165.  * Fixed a bug in dealing with double-colon files.
  166.  * 
  167.  * Revision 1.56  88/06/02  15:22:18  mcgrath
  168.  * Changed RCS rules to give both the RCS filename and the working
  169.  * filename to `co' so the workfile will go in the right place if they
  170.  * have different paths for some weird reason.
  171.  * 
  172.  * Revision 1.55  88/06/02  14:52:47  mcgrath
  173.  * Made pattern_search and selective_vpath_search consider files
  174.  * mentioned in makefiles to be existent even if they are not targets.
  175.  * 
  176.  * Revision 1.54  88/05/31  00:40:34  mcgrath
  177.  * Made recursive variables referenced with $X work right.
  178.  * 
  179.  * Revision 1.53  88/05/30  20:31:20  mcgrath
  180.  * * Made converted single-suffix (".o:", etc.) rules nonterminal.
  181.  * * Added `foreach' and `sort' functions.
  182.  * 
  183.  * Revision 1.52  88/05/29  19:19:15  mcgrath
  184.  * Doubled-up a `%' in a printf format.
  185.  * 
  186.  * Revision 1.51  88/05/26  18:31:37  mcgrath
  187.  * * Removed built-in suffix rules for .? -> .s
  188.  * * Rewrote precious intermediate file pattern stuff to work right.
  189.  * 
  190.  * Revision 1.50  88/05/22  14:48:17  mcgrath
  191.  * Major Beta release before release 2.0.
  192.  * 
  193.  * Revision 1.25  88/05/22  14:29:21  mcgrath
  194.  * Fixed minor bug
  195.  * 
  196.  * Revision 1.24  88/05/21  16:39:54  mcgrath
  197.  * Fixed idiotic (really; I'm losing it) bug in -w stuff.  (sigh)
  198.  * 
  199.  * Revision 1.23  88/05/20  21:38:59  mcgrath
  200.  * Changed to use new globbing function `glob_filename'.
  201.  * 
  202.  * Revision 1.22  88/05/18  23:26:15  mcgrath
  203.  * Fixed stupid incorrect lengths for `filter' and `filter-out'
  204.  * in `function_table'.
  205.  * 
  206.  * Revision 1.21  88/05/18  20:56:55  mcgrath
  207.  * Removed the `struct ruleset' stuff; did extended static rules
  208.  * in a much simpler way.  The new syntax is for example,
  209.  * `*.o: %.o: %.c'.  It is a non-fatal error for the rule target (*.o)
  210.  * not to match the pattern target (%.o).
  211.  * 
  212.  * Revision 1.20  88/05/17  23:10:28  mcgrath
  213.  * Made it a fatal error to use the `LIB((NAME))' syntax.
  214.  * 
  215.  * Revision 1.19  88/05/17  22:30:37  mcgrath
  216.  * Fixed some bugs introduced by the bugfix in the last version (sigh).
  217.  * 
  218.  * Revision 1.18  88/05/16  17:47:01  mcgrath
  219.  * * Changed touching back to reading and writing rather than using utimes.
  220.  * * Changed nonwarranty notice.
  221.  * * Changed the way RCS keywords are handled for version information.
  222.  * 
  223.  * Revision 1.17  88/05/15  17:50:11  mcgrath
  224.  * Made most references to the `name' field of a `struct dep' use
  225.  * the macro `dep_name (d)' which uses `d->name' if it is not nil and
  226.  * `d->file->name' if it is.  This is so that when `snap_deps' makes
  227.  * `struct file's for all the dependencies, further references to their
  228.  * names will use those in the `struct file's which may be changed by
  229.  * VPATH search.
  230.  * 
  231.  * Revision 1.16  88/05/14  15:27:42  mcgrath
  232.  * * Added Emacs c-mode local variables.
  233.  * * A file's modtime is now looked at before implicit rule
  234.  *   search because finding its modtime may change its name via VPATH.
  235.  * * Fixed bug in VPATH pattern recognition that made `%'
  236.  *   matching one char not work.
  237.  * 
  238.  * Revision 1.15  88/05/11  21:29:04  mcgrath
  239.  * Made `$<' be the first dependency of any rule, not just implicit rules.
  240.  * 
  241.  * Revision 1.14  88/05/07  20:32:39  mcgrath
  242.  * * Made all internal functions `static'.
  243.  * * Changed to use new globbing function I added
  244.  *   to glob.c to make it work right.
  245.  * 
  246.  * Revision 1.13  88/05/07  13:44:06  mcgrath
  247.  * Made `touch' use utimes(2) rather than reading and writing.
  248.  * 
  249.  * Revision 1.12  88/05/06  17:13:06  mcgrath
  250.  * Removed SHFLAGS.
  251.  * 
  252.  * Revision 1.11  88/05/04  18:33:34  mcgrath
  253.  * Fixed Fixed bug which caused core dumps when $< was used
  254.  * in a pattern rule with no deps.
  255.  * 
  256.  * Revision 1.10  88/05/04  17:52:40  mcgrath
  257.  * * Made `define' directives make recursive (`='-style) variables.
  258.  * * Removed the `expand' function, since the above change makes in unnecessary.
  259.  * 
  260.  * Revision 1.9  88/05/03  22:27:39  mcgrath
  261.  * * Fixed bug which made recursive expansion not quite work (ack!!).
  262.  * * Made `MAKE' and `MAKEOVERRIDES' be figured out after environment
  263.  *   variables are read in so they will have the right values.
  264.  * * Miscellaneous cosmetic cleanup.
  265.  * 
  266.  * Revision 1.8  88/05/03  16:53:35  mcgrath
  267.  * * Fixed bug in expansion functions code.
  268.  * * Cosmetic changes.
  269.  * 
  270.  * Revision 1.7  88/04/30  15:27:16  mcgrath
  271.  * * Fixed bug which made `ifeq "x" "y"' conditionals fail.
  272.  * * Minor cleanup in conditional_line.
  273.  * 
  274.  * Revision 1.6  88/04/24  00:56:44  roland
  275.  * Removed $($@) automatic macro.
  276.  * 
  277.  * Revision 1.5  88/04/23  21:36:12  roland
  278.  * * Added -v switch the print version information.
  279.  * * Made -w switch be passed in MAKEFLAGS.
  280.  * * Made `main' use exit rather than return (more portable).
  281.  * * Made `pattern_search' and `vpath_search' consider files
  282.  *   mentioned in the makefile but that don't really exist to
  283.  *   be existent only if they are targets in the makefile.
  284.  *   This is the way Unix Make (Sun at least) does it and
  285.  *   it makes more sense.
  286.  * * Given to RMS for beta-testing.
  287.  * 
  288.  Revision 1.4  88/04/23  18:22:28  roland
  289.  * Fixed a minor bug which caused core dumps every time Make ran.
  290.  * Changed all messages to use `...' rather than "...".
  291.  * Given to RMS for beta-testing.
  292.  
  293.  Revision 1.3  88/04/23  17:37:24  roland
  294.  * Changed RCS header stuff slightly (added a keyword).
  295.  * Added support for $(a:-b), etc. as in Sun sh.
  296.  * Fixed bug fix making :: still not work right.
  297.  * Changed format of the message given for -w.
  298.  * Miscellaneous cosmetic cleanup.
  299.  * Added `struct ruleset': contains a chain of rules,
  300.    a pointer to the last rule in the chain, and info about
  301.    the implicit rule limits (which were previously global
  302.    variables).  Pattern rules are put in the ruleset in
  303.    the global variable `global_ruleset'.  There is a chain
  304.    of rulesets which will be listed by -p (if it exists).
  305.    Nothing adds to the chain of rulesets yet.
  306.    The `struct file' has a `ruleset' entry for the set of
  307.    implicit rules that should be used for that file (it should
  308.    be one in the `rulesets' chain) and `pattern_search' will
  309.    honor this entry.
  310.    All of this is the groundwork for `extended static rules' which
  311.    are sets of implicit rules which apply to a given set of files.
  312.    This has not yet been fully implemented because it will need
  313.    a complex design to read in extended static rules (as well as
  314.    a decision of a syntax; `files: %-target: %-deps' is a possibility)
  315.    and put them into rulesets associated with the right files.
  316.    This will be fully implemented sometime in the near future.
  317.  
  318.  *
  319.  */
  320.  
  321. #if 0    /* dummy tags for etags */
  322. endrcs (){}
  323. endlog (){}
  324. #endif
  325.  
  326. #if 0    /* dummy tag for etags  */
  327. flags (){}
  328. #endif
  329.  
  330. /* Flags:
  331.  *    -b ignored for compatability with System V Make
  332.  *    -c change directory
  333.  *    -d debug
  334.  *    -e env_overrides
  335.  *    -f makefile
  336.  *    -i ignore_errors
  337.  *    -k keep_going
  338.  *    -m ignored for compatibility with something or other
  339.  *    -n just_print
  340.  *    -o consider file old
  341.  *    -p print_data_base
  342.  *    -q question
  343.  *    -r no_builtin_rules
  344.  *    -s silent
  345.  *    -S turn off -k
  346.  *    -t touch
  347.  *    -v print version information
  348.  *    -w log working directory
  349.  */
  350.  
  351. #if 0    /* dummy tags for etags */
  352. definitions (){}
  353. defs (){}
  354. #endif
  355.  
  356. #include <signal.h>
  357. #include <stdio.h>
  358. #include <strings.h>
  359.  
  360. #ifdef atarist
  361.  
  362. #include <ctype.h>
  363. #include <types.h>
  364. #include <dir.h>
  365. #include <file.h>
  366. #include <param.h>
  367. #include <stat.h>
  368. /* #include <time.h> */
  369. /* #include <wait.h> */
  370.  
  371. #define abort()    \
  372.     { fprintf(stderr, "Aborting at line %d of file %s\n",    \
  373.         __LINE__, __FILE__); exit(999); }
  374.  
  375. #else
  376.  
  377. #include <sys/types.h>
  378. #include <sys/dir.h>
  379. #include <sys/file.h>
  380. #include <sys/param.h>
  381. #include <sys/stat.h>
  382. #include <sys/time.h>
  383. #include <sys/wait.h>
  384.  
  385. #endif
  386.  
  387. /* Somebody sent this in.  I assume machines that
  388.    pre-define `sparc' will need it.  */
  389. #ifdef    sparc
  390. #include <alloca.h>
  391. #endif    /* sparc    */
  392.  
  393. /* We record the status of a command that got a signal
  394.    as the signal number | 0200 (| 0400 if it got a coredump).  */
  395. #define SIGNAL_STATUS 0200
  396. #define SIGNAL_COREDUMP 0400
  397.  
  398. #define max(a, b) ((a) > (b) ? (a) : (b))
  399. #define min(a, b) ((a) < (b) ? (a) : (b))
  400.  
  401. #ifdef case_insensitive
  402. #define streq(a, b) \
  403.   ((a) == (b) || \
  404.    (char_upcase(*(a)) == char_upcase(*(b)) && \
  405.     (*(a) == '\0' || !ci_strcmp ((a) + 1, (b) + 1))))
  406.  
  407. #else
  408. #define streq(a, b) \
  409.   ((a) == (b) || \
  410.    (*(a) == *(b) && (*(a) == '\0' || !strcmp ((a) + 1, (b) + 1))))
  411. #endif
  412.  
  413. #define file_mtime(f) ((f)->last_mtime != 0 ? (f)->last_mtime : f_mtime (f))
  414. #define initbuffer(lb) (lb)->buffer = (char *) xmalloc ((lb)->size = 200)
  415. #define freebuffer(lb) free ((lb)->buffer)
  416. #define dep_name(d) ((d)->name == 0 ? (d)->file->name : (d)->name)
  417.  
  418. /* The name we were invoked with.  */
  419.  
  420. static char *program;
  421.  
  422. /* A `struct linebuffer' is a structure which holds a line of text.
  423.    `readline' reads a line from a stream into a linebuffer
  424.    and works regardless of the length of the line.  */
  425.  
  426. struct linebuffer
  427.   {
  428.     /* Note:  This is the number of bytes malloc'ed for `buffer'
  429.        It does not indicate `buffer's real length.
  430.        Instead, a losing C asciz null-byte indicates end-of-string */
  431.     long size;
  432.     char *buffer;
  433.   };
  434.  
  435. /* Nonzero => file to delete if fatal signal happens.
  436.    While actually running shell commands, this is their target.  */
  437.  
  438. char *signal_delete_file;
  439.  
  440. /* But only delete the file if it has been changed;
  441.    that is, its mtime is not the same as this.  */
  442.  
  443. long signal_delete_mtime;
  444.  
  445. /* The filename and pointer to line number of the
  446.    makefile currently being read in.  */
  447.  
  448. char *reading_filename;
  449. long *reading_lineno_ptr;
  450.  
  451. /* Structure that gives the commands to make a file
  452.    and information about where these commands came from.  */
  453.  
  454. struct commands
  455.   {
  456.     char *filename;        /* file that contains commands */
  457.     long lineno;        /* line number in file */
  458.     char *commands;        /* commands text */
  459.   };
  460.  
  461. /* Structure that represents the info on one file
  462.    that the makefile says how to make.
  463.    All of these are chained together through `next'.  */
  464.  
  465. struct file
  466.   {
  467.     struct file *next;
  468.     char *name;
  469.     struct dep *deps;
  470.     struct commands *cmds;    /* Commands to execute for this target */
  471.     char *stem;            /* common stem, if an implicit
  472.                        rule has been used */
  473.     int update_status;        /* Status of the last attempt to update,
  474.                    or -1 if none has been made.  */
  475.     long last_mtime;        /* File's modtime, if already known.  */
  476.     struct file *prev;        /* Previous entry for same file name;
  477.                    used when there are multiple double-colon
  478.                    entries for the same file.  */
  479.     char double_colon;        /* Nonzero for double-colon entry */
  480.     char precious;        /* Non-0 means don't delete this file on quit */
  481.     char recursive;        /* Non-0 means do this file's commands
  482.                        even if -q, -t or -n.  */
  483.     char tried_implicit;    /* Nonzero if have searched for implicit rule
  484.                    for making this file; don't search again */
  485.     char updating;        /* Nonzero while updating deps of this file */
  486.     char updated;        /* Nonzero if this file has been remade.  */
  487.     char is_target;        /* Nonzero if file is described as target */
  488.     char phony;            /* Nonzero if this is a phony file
  489.                    ie, a dependent of .PHONY.  */
  490.     char intermediate;        /* Nonzero if this is an intermediate file.  */
  491.   };
  492.  
  493. /* Number of intermediate files entered.  */
  494.  
  495. int num_intermediates;
  496.  
  497. /* Hash table of files the makefile knows how to make.  */
  498.  
  499. #define FILE_BUCKETS    53
  500. struct file *files[FILE_BUCKETS];
  501.  
  502. /* Hash table of files in the various directories.
  503.    This makes file_exists_p faster for files in these directories.  */
  504.  
  505. struct dirdata
  506. {
  507.   struct dirdata *next;
  508.   char *dir;            /* Name of directory */
  509.   char *name;            /* 
  510.   int impossible;        /* This file is impossible */
  511. };
  512.  
  513. #define DIR_HASH_SIZE 1007
  514.  
  515. struct dirdata *dir_hash_table[DIR_HASH_SIZE];
  516.  
  517. /* Structure used for pattern rules.  */
  518.  
  519. struct rule
  520.   {
  521.     struct rule *next;
  522.     char *name;            /* Name (target) of the rule  */
  523.     int namelen;        /* Length of that string; to save time */
  524.     char *patsuffix;        /* Pointer to char after %  */
  525.     struct dep *deps;        /* Dependents of the rule  */
  526.     struct commands *cmds;    /* Commands to execute  */
  527.     char recursive;        /* If commands contain "$(MAKE)"  */
  528.     char terminal;        /* If terminal (double colon)  */
  529.     char subdir;        /* If references nonexistent subdirectory  */
  530.     char in_use;        /* If in use by a parent pattern_search  */
  531.   };
  532.  
  533.  
  534. /* Chain of all pattern rules  */
  535.  
  536. struct rule *pattern_rules;
  537.  
  538. /* Pointer to last rule in the chain, so we can add onto the end  */
  539.  
  540. struct rule *last_pattern_rule;
  541.  
  542. /* Number of rules in the chain  */
  543.  
  544. int num_pattern_rules;
  545.  
  546. /* Maximum number of dependencies of any pattern rule  */
  547.  
  548. int max_pattern_deps;
  549.  
  550. /* Maximum length of the name of a dependencies of any pattern rule  */
  551.  
  552. int max_pattern_dep_length;
  553.  
  554. /* Structure used to represent a selective VPATH searchpath.  */
  555.  
  556. struct vpath
  557.   {
  558.     struct vpath *next;    /* Pointer to next struct in the linked list.  */
  559.     char *pattern;    /* The pattern to match.  */
  560.     int patlen;        /* Length of the pattern.  */
  561.     char *patsuffix;    /* Pointer to the char after `%' in pattern.  */
  562.     char **searchpath;    /* Null-terminated list of directories.  */
  563.     int maxlen;        /* Maximum length of any entry in the list.  */
  564.   };
  565.  
  566. /* Linked-list of all selective VPATHs.  */
  567.  
  568. struct vpath *vpaths;
  569.  
  570. /* Structure for the general VPATH given in the macro.  */
  571.  
  572. struct vpath *general_vpath;
  573.  
  574. /* Incremented when we find a file needs to be remade,
  575.    even if it has no commands or if we are not really executing commands.  */
  576.  
  577. int files_remade;
  578.  
  579. /* Structure representing one dependency of a file.
  580.    Each struct file's `deps' points to a chain of these,
  581.    chained through the `next'.
  582.  
  583.    Note that the first three words of this match a struct nameseq.  */
  584.  
  585. struct dep
  586.   {
  587.     struct dep *next;
  588.     char *name;
  589.     int quotedparen;
  590.     struct file *file;
  591.     int changed;
  592.   };
  593.  
  594. /* Structure used in chains of names, for parsing and globbing */
  595.  
  596. struct nameseq
  597.   {
  598.     struct nameseq *next;
  599.     char *name;
  600.     int quotedparen;
  601.   };
  602.  
  603. /* First file defined in the makefile whose name does not
  604.    start with `.'.  This is the default to remake if the
  605.    command line does not specify.  */
  606.  
  607. struct file *default_goal_file;
  608.  
  609. /* Pointer to structure for the file .SUFFIXES
  610.    whose dependencies are the suffixes to be searched.  */
  611.  
  612. struct file *suffix_file;
  613.  
  614. /* Maximum length of a suffix.  */
  615.  
  616. int maxsuffix;
  617.  
  618. /* Pointer to structure for the file .DEFAULT
  619.    whose commands are used for any file that has none of its own.
  620.    This is zero if the makefiles do not define .DEFAULT.  */
  621.  
  622. struct file *default_file;
  623.  
  624. /* Codes in a macro definition saying where the definition came from.
  625.    Increasing numeric values signify less-overridable definitions.  */
  626. enum macro_origin
  627.   {
  628.     o_env,        /* Macro from environment.  */
  629.     o_file,        /* Macro given in a makefile.  */
  630.     o_env_override,    /* Macro from environment, if -e.  */
  631.     o_command,        /* Macro given by user.  */
  632.     o_override,     /* Macro from an `override' directive in a makefile.  */
  633.   };
  634.  
  635. /* Structure that represents one macro definition.
  636.    Each bucket of the hash table `macros' is a chain of these,
  637.    chained through `next'.  */
  638.  
  639. struct macro
  640.   {
  641.     struct macro *next;        /* Link the chain  */
  642.     char *name;            /* Macro name  */
  643.     char *value;        /* Macro value  */
  644.     enum macro_origin origin;    /* Macro origin  */
  645.     char recursive;        /* Gets recursively re-evaluated  */
  646.     char expanding;        /* Is currently expanding  */
  647.   };
  648.  
  649. /* Hash table of all macro definitions.  */
  650.  
  651. #define MACRO_BUCKETS    43
  652. struct macro *macros[MACRO_BUCKETS];
  653.  
  654. /* Pointers to struct macro's for the built-in macros,
  655.    $*, $@, $<, $% and their F and D pairs, $^ and $?, and $($/).   */
  656.  
  657. struct macro *star_macro, *starF_macro, *starD_macro;
  658. struct macro *at_macro, *atF_macro, *atD_macro;
  659. struct macro *less_macro, *lessF_macro, *lessD_macro;
  660. struct macro *percent_macro, *percentF_macro, *percentD_macro;
  661. struct macro *caret_macro, *qmark_macro;
  662. struct macro *dollar_slash_macro;
  663.  
  664. /* Pointer to struct macro for SHELL.  So we can look up the value fast.  */
  665.  
  666. struct macro *shell_macro;
  667.  
  668. /* Pointer to struct macro for IFS (sh internal field separator).  */
  669.  
  670. struct macro *ifs_macro;
  671.  
  672. /* Value of the MAKELEVEL macro at startup (or 0).  */
  673.  
  674. int makelevel;
  675.  
  676. /* The next two describe the macro output buffer.
  677.    This buffer is used to hold the macro-expansion of a line of the makefile.
  678.    It is made bigger with realloc whenever it is too small.
  679.    macro_buffer_length is the size currently allocated.
  680.    macro_buffer is the address of the buffer.  */
  681.  
  682. unsigned macro_buffer_length;
  683. char *macro_buffer;
  684.  
  685. /* Values of command-line options.  */
  686.  
  687. /* Nonzero means do not print commands to be executed (-s).  */
  688.  
  689. int silent_flag;
  690.  
  691. /* Nonzero means just touch the files
  692.    that would appear to need remaking (-t)  */
  693.  
  694. int touch_flag;
  695.  
  696. /* Nonzero means just print what commands would need to be executed,
  697.    don't actually execute them (-n).  */
  698.  
  699. int just_print_flag;
  700.  
  701. /* Print debugging trace info (-d).  */
  702.  
  703. int debug_flag;
  704.  
  705. /* Environment macros override makefile definitions.  */
  706.  
  707. int env_overrides;
  708.  
  709. /* Nonzero means ignore status codes returned by commands
  710.    executed to remake files.  Just treat them all as successful (-i).  */
  711.  
  712. int ignore_errors_flag;
  713.  
  714. /* Nonzero means don't remake anything, just print the data base
  715.    that results from reading the makefile (-p).  */
  716.  
  717. int print_data_base_flag;
  718.  
  719. /* Nonzero means don't remake anything; just return a nonzero status
  720.    if the specified targets are not up to date (-q).  */
  721.  
  722. int question_flag;
  723.  
  724. /* Nonzero means do not use any of the builtin rules (-r).  */
  725.  
  726. int no_builtin_rules_flag;
  727.  
  728. /* Nonzero means keep going even if remaking some file fails (-k).  */
  729.  
  730. int keep_going_flag;
  731.  
  732. /* Nonzero means print working directory before starting and after
  733.    finishing make. */
  734.  
  735. int print_directory_flag;
  736.  
  737. /* Nonzero means print version information.  */
  738.  
  739. int print_version_flag;
  740.  
  741. #if 0    /* dummy tags for etags */
  742. declarations (){}
  743. decls (){}
  744. #endif
  745.  
  746. /* Forward declarations */
  747.  
  748. static struct macro *define_macro ();
  749. static struct macro *lookup_macro ();
  750. static char *macro_expand ();
  751. static char *macro_buffer_output ();
  752. static int try_macro_definition ();
  753. static long do_define ();
  754. static struct file *enter_file ();
  755. static struct file *lookup_file ();
  756. static int update_file ();
  757. static long readline ();
  758. static void print_spaces ();
  759. static long f_mtime (), name_mtime (), library_file_mtime ();
  760. static int vpath_search ();
  761. static char *savestring (), *concat ();
  762. static char *xmalloc (), *xrealloc ();
  763. static char *alloca ();
  764. static char *sindex (), *lindex (), *wstok ();
  765. static char *string_glob ();
  766. static char *end_of_token (), *next_token (), *find_next_token ();
  767. static void new_environ ();
  768. static void fatal (), error (), perror_with_name (), pfatal_with_name ();
  769. static struct nameseq *parse_file_seq ();
  770. static struct nameseq *multi_glob ();
  771. static void decode_switches ();
  772. static void define_automatic_macros ();
  773. static void print_data_base ();
  774. static void read_all_makefiles ();
  775. static struct dep *copy_dep_chain ();
  776. static int conditional_line ();
  777. static void snap_deps ();
  778. static struct vpath *construct_vpath_list ();
  779. static void build_vpath_lists ();
  780. static void construct_include_path ();
  781. static void dir_load ();
  782. static void file_impossible ();
  783. static int file_impossible_p ();
  784. static void convert_to_pattern ();
  785. static void new_pattern_rule ();
  786. static void install_pattern_rule ();
  787. static void count_implicit_rule_limits ();
  788. static int pattern_search ();
  789.  
  790. static int update_file_1 (), execute_file_commands (), try_implicit_rule ();
  791. static int execute_command_line ();
  792.  
  793. static void log_working_directory ();
  794. static void print_version ();
  795.  
  796. static int alpha_compare ();
  797. static int ar_name ();
  798. static int ar_touch (), ar_scan_1 ();
  799. extern int ar_scan (), ar_member_touch ();
  800.  
  801. extern char **glob_filename ();
  802.  
  803. extern char *getwd ();
  804. extern long time ();
  805.  
  806. /* Data base of implicit rules */
  807.  
  808. /* For calling install_pattern_rule.  */
  809. struct pspec {char *target, *dep, *commands;};
  810.  
  811. /* This is the default list of suffixes for suffix rules.
  812.    `.s' must come last, so that a `.o' file will be made from
  813.    a `.c' or `.p' or ... file rather than from a .s file.  */
  814.  
  815. #ifdef atarist
  816. char *default_suffixes = ".ttp .olb .o .c .y .ye .yr .l .F .e .r .f .p .h .s";
  817. #else
  818. char *default_suffixes = ".out .a .o .c .y .ye .yr .l .F .e .r .f .p .h .s";
  819. #endif
  820.  
  821. struct pspec default_pattern_rules[] =
  822.   {
  823.     "(%)", "%",
  824.     "ar r $@ $<",
  825.  
  826.     /* The X.out rules are only in BSD's default set because
  827.        BSD Make has no null-suffix rules, so `foo.out' and
  828.        `foo' are the same thing.  */
  829.     "%.out", "%",
  830.     "@rm -f $@ \n cp $< $@",
  831.  
  832.     /* For libraries, so they won't get ranlib'd unnecessarily.  */
  833.     "%(__.SYMDEF)", "%",
  834.     "$(RANLIB) $<",
  835.  
  836.     0, 0, 0
  837.   };
  838.  
  839. struct pspec default_terminal_rules[] =
  840.   {
  841.     /* RCS  */
  842.     "%", "%,v",
  843.     "$(CO) $(COFLAGS) $< $@",
  844.     "%", "RCS/%,v",
  845.     "$(CO) $(COFLAGS) $< $@",
  846.  
  847.     /* SCCS  */
  848.     "%", "s.%",
  849.     "$(GET) $(GFLAGS) $<",
  850.     "%", "SCCS/s.%",
  851.     "$(GET) $(GFLAGS) $<",
  852.  
  853.     0, 0, 0
  854.   };
  855.  
  856. char *default_suffix_rules[] =
  857.   {
  858.     ".o",
  859.     "$(CC) $(LDFLAGS) $^ $(LOADLIBES) -o $@",
  860.     ".s",
  861.     "$(CC) $(ASFLAGS) $(LDFLAGS) $^ $(LOADLIBES) -o $@",
  862.     ".c",
  863.     "$(CC) $(CFLAGS) $(LDFLAGS) $^ $(LOADLIBES) -o $@",
  864.     ".f",
  865.     "$(FC) $(FFLAGS) $(LDFLAGS) $^ $(LOADLIBES) -o $@",
  866.     ".p",
  867.     "$(PC) $(PFLAGS) $(LDFLAGS) $^ $(LOADLIBES) -o $@",
  868.     ".F",
  869.     "$(FC) $(FFLAGS) $(LDFLAGS) $^ $(LOADLIBES) -o $@",
  870.     ".e",
  871.     "$(FC) $(FFLAGS) $(LDFLAGS) $^ $(LOADLIBES) -o $@",
  872.     ".r",
  873.     "$(FC) $(FFLAGS) $(LDFLAGS) $^ $(LOADLIBES) -o $@",
  874.  
  875.     ".s.o",
  876.     "$(AS) $(ASFLAGS) $< -o $@",
  877.     ".c.o",
  878.     "$(CC) $(CFLAGS) -c $< -o $@",
  879.     ".f.o",
  880.     "$(FC) $(FFLAGS) -c $< -o $@",
  881.     ".p.o",
  882.     "$(PC) $(PFLAGS) -c $< -o $@",
  883.     ".F.o",
  884.     "$(FC) $(FFLAGS) -c $< -o $@",
  885.     ".e.o",
  886.     "$(EC) $(EFLAGS) -c $< -o $@",
  887.     ".r.o",
  888.     "$(RC) $(RFLAGS) -c $< -o $@",
  889.  
  890.     ".y.c",
  891.     "$(YACC) $(YFLAGS) $< \n mv -f y.tab.c $@",
  892.     ".l.c",
  893.     "$(LEX) $(LFLAGS) $< \n mv -f lex.yy.c $@",
  894.  
  895.     ".F.f",
  896.     "$(FC) $(FFLAGS) -F $< -o $@",
  897.     ".e.f",
  898.     "$(EC) $(EFLAGS) -F $< -o $@",
  899.     ".r.f",
  900.     "$(RC) $(RFLAGS) -F $< -o $@",
  901.  
  902.     ".ye.e",
  903.     "$(YACCE) $(YFLAGS) $< \n mv -f y.tab.e $@",
  904.  
  905.     ".yr.r",
  906.     "$(YACCR) $(YFLAGS) $< \n mv -f y.tab.r $@",
  907.     /* This might actually make lex.yy.c if there's no %R%
  908.        directive in $*.l, but in that case why were you
  909.        trying to make $*.r anyway?  */
  910.     ".l.r",
  911.     "$(LEX) $(LFLAGS) $< \n mv -f lex.yy.r $@",
  912.  
  913.     0
  914.   };
  915.  
  916. char *default_macros[] =
  917.   {
  918.     "AS", "as",
  919.     "CC", "cc",
  920.     "CO", "co",
  921.     "EC", "f77",
  922.     "FC", "f77",
  923.     "GET", "get",
  924.     "LEX", "lex",
  925. #ifdef atarist
  926.     "RANLIB", "ar sr",
  927. #else
  928.     "RANLIB", "ranlib",
  929. #endif
  930.     "RC", "f77",
  931.     "PC", "pc",
  932.     "YACC", "yacc",    /* Or "bison -y"  */
  933.     "YACCE", "yacc -e",
  934.     "YACCR", "yacc -r",
  935.     0
  936.   };
  937.  
  938. /* Default directories to search for include files in  */
  939.  
  940. #ifdef atarist
  941. char *default_include_directories[] =
  942.   {
  943.     "d:\\gnu\\lib",
  944.     0
  945.   };
  946. #else
  947. char *default_include_directories[] =
  948.   {
  949.     "/usr/gnu/include",
  950.     "/usr/local/include",
  951.     "/usr/include",
  952.     0
  953.   };
  954. #endif
  955.  
  956. /* List of directories to search for include files in  */
  957.  
  958. char **include_directories;
  959.  
  960. /* Maximum length of an element of the above.  */
  961.  
  962. int max_incl_len;
  963.  
  964. #if 0    /* dummy tag for etags    */
  965. code (){}
  966. #endif
  967.  
  968. /* Handle bus errors, illegal instruction, etc. */
  969. static
  970. fatal_error_signal (sig)
  971.      int sig;
  972. {
  973.   struct stat st;
  974.  
  975. #ifndef atarist
  976.   signal (sig, SIG_DFL);
  977.   (void) sigsetmask (0);
  978.  
  979.   /* Don't die until our children have finished dying.  */
  980.   while (wait ((union wait *) 0) != -1)
  981.     ;
  982. #endif
  983.  
  984.   /* If we have specified a file to delete for this moment,
  985.      and it exists and is not a directory, delete it.  */
  986.  
  987.   if (signal_delete_file
  988.       && stat (signal_delete_file, &st) >= 0
  989.       && (st.st_mode & S_IFMT) != S_IFDIR
  990.       && st.st_mtime != signal_delete_mtime)
  991.     {
  992.       fprintf (stderr, "\n%s: Deleting file %s\n",
  993.            program, signal_delete_file);
  994.       fflush (stderr);
  995.       if (unlink (signal_delete_file) < 0)
  996.     perror_with_name ("unlink: ", signal_delete_file);
  997.     }
  998.  
  999.   /* Delete any non-precious intermediate files that were made.  */
  1000.  
  1001.   if (num_intermediates > 0)
  1002.     {
  1003.       register int i;
  1004.       register struct file *f;
  1005.  
  1006.       /* Examine each `struct file' in the hash table.  */
  1007.       for (i = 0; i < FILE_BUCKETS; ++i)
  1008.     for (f = files[i]; f != 0; f = f->next)
  1009.       if (f->intermediate && !f->precious && f->updated)
  1010.         {
  1011.           fprintf (stderr, "%s: Deleting file %s\n", program, f->name);
  1012.           fflush (stderr);
  1013.           if (!just_print_flag && unlink (f->name) < 0)
  1014.         perror_with_name ("unlink: ", f->name);
  1015.         }
  1016.     }
  1017.  
  1018.   /* Signal the same code; this time it will really be fatal.  */
  1019.  
  1020. #ifdef atarist
  1021. /* ... I think this is just an obscure way to exit ... */
  1022.   exit(sig);
  1023. #else
  1024.   if (kill (getpid (), sig) < 0)
  1025.     /* It shouldn't return, but if it does, die anyway.  */
  1026.     pfatal_with_name ("kill");
  1027. #endif
  1028. }
  1029.  
  1030. int
  1031. main (argc, argv, envp)
  1032.      int argc;
  1033.      char **argv;
  1034.      char **envp;
  1035. {
  1036.   register struct file *f;
  1037.   register int i;
  1038.   int num_remade = 0;
  1039.   int status = 0;
  1040.   int this_status;
  1041.   register char *cmd_defs;
  1042.   register int cmd_defs_len, cmd_defs_idx;
  1043.  
  1044.   bzero ((char *) files, sizeof files);
  1045.   bzero ((char *) macros, sizeof macros);
  1046.   bzero ((char *) dir_hash_table, sizeof dir_hash_table);
  1047.  
  1048.   files_remade = 0;
  1049.   macro_buffer = 0;
  1050.   default_goal_file = 0;
  1051.   signal_delete_file = 0;
  1052.   signal_delete_mtime = 0;
  1053.   reading_filename = 0;
  1054.   reading_lineno_ptr = 0;
  1055.   num_intermediates = 0;
  1056.   vpaths = 0;
  1057.   general_vpath = 0;
  1058.   pattern_rules = last_pattern_rule = 0;
  1059.   
  1060.   signal (SIGHUP, fatal_error_signal);
  1061.   signal (SIGQUIT, fatal_error_signal);
  1062.   signal (SIGINT, fatal_error_signal);
  1063.   signal (SIGILL, fatal_error_signal);
  1064.   signal (SIGTRAP, fatal_error_signal);
  1065.   signal (SIGIOT, fatal_error_signal);
  1066.   signal (SIGEMT, fatal_error_signal);
  1067.   signal (SIGFPE, fatal_error_signal);
  1068.   signal (SIGBUS, fatal_error_signal);
  1069.   signal (SIGSEGV, fatal_error_signal);
  1070.   signal (SIGSYS, fatal_error_signal);
  1071.   signal (SIGTERM, fatal_error_signal);
  1072. #ifdef SIGXCPU
  1073.   signal (SIGXCPU, fatal_error_signal);
  1074. #endif
  1075. #ifdef SIGXFSZ
  1076.   signal (SIGXFSZ, fatal_error_signal);
  1077. #endif
  1078.  
  1079. #ifdef atarist
  1080.   program = "make";
  1081. #else
  1082.   if (argv[0] == 0)
  1083.     program = "make";
  1084.   else 
  1085.     {
  1086.       program = rindex (argv[0], '/');
  1087.       if (program == 0)
  1088.     program = argv[0];
  1089.       else
  1090.     ++program;
  1091.     }
  1092. #endif
  1093.  
  1094.   /* Read in macros from the environment.  It is important that this be
  1095.      done before `MAKE' and `MAKEOVERRIDES' are figured out so their
  1096.      definitions will not be ones from the environment.  */
  1097.  
  1098.   for (i = 0; envp[i] != 0; ++i)
  1099.     {
  1100.       register char *ep = envp[i];
  1101.       while (*ep++ != '=')
  1102.     ;
  1103.       define_macro (envp[i], ep - envp[i] - 1, ep,
  1104.             env_overrides ? o_env_override : o_env, 1);
  1105.     }
  1106.  
  1107.   /* Search for command line arguments that define macros,
  1108.      and do the definitions.  Also save up the text of these
  1109.      arguments in CMD_DEFS so we can put them into the values
  1110.      of $(MAKEOVERRIDES) and $(MAKE).  */
  1111.  
  1112.   cmd_defs_len = 100;
  1113.   cmd_defs = (char *) xmalloc (cmd_defs_len);
  1114.   cmd_defs_idx = 0;
  1115.  
  1116.   for (i = 1; i < argc; i++)
  1117.     {
  1118.       /* Don't even try an arg that is a switch.  */
  1119.       if (!strcmp (argv[i], "-f") || !strcmp (argv[i], "-o"))
  1120.     i++;
  1121.       else if (argv[i][0] != '-')
  1122.     {
  1123.       /* It's not a switch; try it as a macro definition.  */
  1124.       if (try_macro_definition (argv[i], o_command))
  1125.         {
  1126.           /* It succeeded.  The macro is already defined.
  1127.          Backslash-quotify it and append it to CMD_DEFS,
  1128.          then clobber it to `-' in ARGV
  1129.          so that it won't be taken for a goal target.  */
  1130.           register char *p = argv[i];
  1131.           int l = strlen (p);
  1132.           if (cmd_defs_len - ((l * 2) + 1) < 0)
  1133.         {
  1134.           cmd_defs_len += l * 2;
  1135.           cmd_defs = (char *) xrealloc (cmd_defs, cmd_defs_len);
  1136.         }
  1137.           while (*p)
  1138.         {
  1139.           if (index ("'\"*?[]$<>(){}|&~`\\ \t\r\n\f\v", *p) != 0)
  1140.             cmd_defs[cmd_defs_idx++] = '\\';
  1141.           cmd_defs[cmd_defs_idx++] = *p++;
  1142.         }
  1143.           cmd_defs[cmd_defs_idx++] = ' ';
  1144.           argv[i] = "-";
  1145.         }
  1146.     }
  1147.     }
  1148.  
  1149.   if (cmd_defs_idx > 0)
  1150.     {
  1151.       cmd_defs[cmd_defs_idx] = '\0';
  1152.       define_macro ("MAKEOVERRIDES", 13, cmd_defs, o_override, 0);
  1153.     }
  1154.  
  1155.   /* Set the "MAKE" macro to the name we were invoked with.
  1156.      (If it is a relative pathname with a slash, prepend our directory name
  1157.      so the result will run the same program regardless of current dir.
  1158.      If it is a name with no slash, we can only hope that PATH did not
  1159.      find it in the current directory.)
  1160.  
  1161.      Append at the end the command-line macro definitions gathered above
  1162.      so sub-makes get them as command-line definitions.  */
  1163.  
  1164. #ifdef atarist
  1165.   if (argv[0] != 0 && argv[0][0] != '\\' && index (argv[0], '\\') != 0)
  1166. #else
  1167.   if (argv[0] != 0 && argv[0][0] != '/' && index (argv[0], '/') != 0)
  1168. #endif
  1169.     {
  1170.       char dir[MAXPATHLEN];
  1171.       char *str;
  1172.       if (getwd (dir) == 0)
  1173.     {
  1174.       error ("getwd: %s", dir);
  1175.       dir[0] = '\0';
  1176.     }
  1177. #ifdef atarist
  1178.       str = concat (dir, "\\", argv[0]);
  1179. #else
  1180.       str = concat (dir, "/", argv[0]);
  1181. #endif
  1182.       if (cmd_defs_idx > 0)
  1183.     {
  1184.       char *s = concat (str, " ", cmd_defs);
  1185.       free (str);
  1186.       str = s;
  1187.     }
  1188.       define_macro ("MAKE", 4, str, o_env, 0);
  1189.       free (str);
  1190.     }
  1191.   else if (cmd_defs_idx > 0)
  1192.     {
  1193.       char *str = concat (argv[0], " ", cmd_defs);
  1194.       define_macro ("MAKE", 4, str, o_env, 0);
  1195.       free (str);
  1196.     }
  1197.   else
  1198.     define_macro ("MAKE", 4, argv[0], o_env, 0);
  1199.  
  1200.   free (cmd_defs);
  1201.  
  1202.   /* Decode the switches now */
  1203.  
  1204.   decode_switches (argc, argv);
  1205.  
  1206.   /* Parse any -c flags and move ourselves about.  */
  1207.  
  1208.   for (i = 1; i < argc; ++i)
  1209.     if (!strcmp (argv[i], "-c"))
  1210.       {
  1211.     ++i;
  1212.     if (i >= argc)
  1213.       fatal ("no directory given after -c command switch");
  1214.     if (chdir (argv[i]) < 0)
  1215.       pfatal_with_name (argv[i]);
  1216.       }
  1217.  
  1218.   /* Now that we know the default directory, hash its contents.  */
  1219.  
  1220.   if (print_directory_flag)
  1221.     log_working_directory (1);
  1222.  
  1223.   dir_load (".");
  1224.  
  1225.   /* Define the initial list of suffixes for old-style rules.  */
  1226.  
  1227.   suffix_file = enter_file (".SUFFIXES");
  1228.  
  1229.   if (!no_builtin_rules_flag)
  1230.     {
  1231.       char *ptr;
  1232.       char **p1;
  1233.  
  1234.       ptr = default_suffixes;
  1235.       /* Why do multi-glob here?  None of the suffixes contains *.
  1236.      But multi-glob is easiest way of reversing the chain.  */
  1237.       suffix_file->deps
  1238.     = (struct dep *) multi_glob (parse_file_seq (&ptr, '\0',
  1239.                              sizeof (struct dep)),
  1240.                      sizeof (struct dep));
  1241.  
  1242.       /* Enter the suffix rules as files.  */
  1243.       for (p1 = default_suffix_rules; *p1;)
  1244.     {
  1245.       struct file *f = enter_file (*p1++);
  1246.  
  1247.       f->cmds = (struct commands *) xmalloc (sizeof (struct commands));
  1248.       f->cmds->commands = *p1++;
  1249.       f->cmds->filename = 0;
  1250.       f->cmds->lineno = 0;
  1251.     }
  1252.  
  1253.       /* Install the default macro definitions (CC, etc.)  */
  1254.       for (p1 = default_macros; *p1;)
  1255.     {
  1256.       char *name = *p1++;
  1257.       define_macro (name, strlen (name), *p1++, o_file, 0);
  1258.     }
  1259.     }
  1260.  
  1261.   /* Define some internal and special macros.  */
  1262.  
  1263.   define_automatic_macros ();
  1264.  
  1265.   /* Read all the specified or default makefiles */
  1266.  
  1267.   read_all_makefiles (argc, argv);
  1268.  
  1269.   ignore_errors_flag = ignore_errors_flag || lookup_file (".IGNORE");
  1270.  
  1271.   silent_flag = silent_flag || lookup_file (".SILENT");
  1272.  
  1273.   default_file = lookup_file (".DEFAULT");
  1274.  
  1275.   /* Mark files given with -o flags as very old (00:00:01.00 Jan 1, 1970)
  1276.      and as having been updated already.  */
  1277.  
  1278.   for (i = 1; i < argc; ++i)
  1279.     if (argv[i][0] == '-' && argv[i][1] == 'o' && argv[i][2] == '\0')
  1280.       {
  1281.     struct file *f;
  1282.     ++i;
  1283.     if (i >= argc)
  1284.       fatal ("no file name given after -o flag");
  1285.     f = enter_file (argv[i]);
  1286.     f->last_mtime = 1L;
  1287.     f->updated = 1;
  1288.     f->update_status = 0;
  1289.       }
  1290.  
  1291.   /* Make each `struct dep' point at the `struct file'
  1292.      for the file depended on.  */
  1293.  
  1294.   snap_deps ();
  1295.  
  1296.   /* Install the default pattern rules.  */
  1297.  
  1298.   if (!no_builtin_rules_flag)
  1299.     {
  1300.       struct pspec *p;
  1301.       /* Install the default pattern rules.  */
  1302.       for (p = default_pattern_rules; p->target != 0; ++p)
  1303.     install_pattern_rule (p, 0);
  1304.       /* Install the default terminal (RCS and SCCS) rules.  */
  1305.       for (p = default_terminal_rules; p->target != 0; ++p)
  1306.     install_pattern_rule (p, 1);
  1307.     }
  1308.  
  1309.   /* Convert old-style suffix rules to pattern rules.  */
  1310.   convert_to_pattern ();
  1311.  
  1312.   /* Compute max dep length and max # deps of any implicit rule.  */
  1313.   count_implicit_rule_limits ();
  1314.  
  1315.   /* Construct the listings of directories in VPATH lists.  */
  1316.   build_vpath_lists ();
  1317.  
  1318.   /* Construct the list of include directories to search.  */
  1319.   construct_include_path (argc, argv);
  1320.  
  1321.   if (print_data_base_flag)
  1322.     print_data_base ();
  1323.   else if (print_version_flag)
  1324.     /* We don't print the version under -p
  1325.        because print_data_base does it.  */
  1326.     print_version ();
  1327.  
  1328.   /* Search command line for files to remake.  */
  1329.  
  1330.   for (i = 1; i < argc; i++)
  1331.     {
  1332.       /* Anything not a switch or an argument of a switch
  1333.      is a file to be remade.
  1334.      Note that macro definition args were replaced with
  1335.      dummies that look like switches.  */
  1336.       if (!strcmp (argv[i], "-f") || !strcmp (argv[i], "-c")
  1337.           || !strcmp (argv[i], "-o") || !strcmp (argv[i], "-I"))
  1338.     ++i;
  1339.       else if (argv[i][0] != '-')
  1340.     {
  1341.       f = enter_file (argv[i]);
  1342.       num_remade++;
  1343.       this_status = update_file (f, 0);
  1344.       if (this_status)
  1345.         {
  1346.           status = this_status;
  1347.           if (!keep_going_flag)
  1348.         break;
  1349.         }
  1350.     }
  1351.     }
  1352.  
  1353.   /* Command line did not specify any file to remake => use default.  */
  1354.  
  1355.   if (num_remade == 0)
  1356.     {
  1357.       if (default_goal_file)
  1358.     status = update_file (default_goal_file, 0);
  1359.       else
  1360.     fatal ("no target");
  1361.     }
  1362.  
  1363.   /* Remove the intermediate files.  */
  1364.  
  1365.   if (num_intermediates > 0)
  1366.     for (i = 0; i < FILE_BUCKETS; ++i)
  1367.       {
  1368.     register struct file *f;
  1369.     for (f = files[i]; f != 0; f = f->next)
  1370.       if (f->intermediate && !f->precious && f->updated)
  1371.         {
  1372.           if (!silent_flag)
  1373.         printf ("rm -f %s\n", f->name);
  1374.           if (!just_print_flag && unlink (f->name) < 0)
  1375.         perror_with_name ("unlink: ", f->name);
  1376.         }
  1377.       }
  1378.  
  1379.   if (print_directory_flag)
  1380.     log_working_directory (0);
  1381.  
  1382.   exit (status);
  1383.   /* NOTREACHED */
  1384. }
  1385.  
  1386. static void
  1387. decode_switches (argc, argv)
  1388.      int argc;
  1389.      char **argv;
  1390. {
  1391.   register int i;
  1392.   register char *sw;
  1393.   char keptflag;
  1394.   void decode_env_switches ();
  1395.  
  1396.   debug_flag = 0;
  1397.   env_overrides = 0;
  1398.   ignore_errors_flag = 0;
  1399.   keep_going_flag = 0;
  1400.   just_print_flag = 0;
  1401.   print_data_base_flag = 0;
  1402.   question_flag = 0;
  1403.   no_builtin_rules_flag = 0;
  1404.   silent_flag = 0;
  1405.   touch_flag = 0;
  1406.   print_directory_flag = 0;
  1407.   print_version_flag = 0;
  1408.  
  1409.   decode_env_switches ("MAKEFLAGS", 9);
  1410.   decode_env_switches ("MFLAGS", 5);
  1411.  
  1412.   for (i = 1; i < argc; i++)
  1413.     {
  1414.       keptflag = '\0';
  1415.       sw = argv[i];
  1416.       if (*sw++ == '-')
  1417.     while (*sw)
  1418.       switch (*sw++)
  1419.         {
  1420.         case 'b':
  1421.         case 'm':
  1422.           break;
  1423.         case 'c':
  1424.           keptflag = 'c';
  1425.           break;
  1426.         case 'd':
  1427.           debug_flag = 1;
  1428.           break;
  1429.         case 'e':
  1430.           env_overrides = 1;
  1431.           break;
  1432.         case 'f':
  1433.           keptflag = 'f';
  1434.           break;
  1435.         case 'I':
  1436.           keptflag = 'I';
  1437.           break;
  1438.         case 'i':
  1439.           ignore_errors_flag = 1;
  1440.           break;
  1441.         case 'k':
  1442.           keep_going_flag = 1;
  1443.           break;
  1444.         case 'n':
  1445.           just_print_flag = 1;
  1446.           break;
  1447.         case 'o':
  1448.           keptflag = 'o';
  1449.           break;
  1450.         case 'p':
  1451.           print_data_base_flag = 1;
  1452.           break;
  1453.         case 'q':
  1454.           question_flag = 1;
  1455.           break;
  1456.         case 'r':
  1457.           no_builtin_rules_flag = 1;
  1458.           break;
  1459.         case 's':
  1460.           silent_flag = 1;
  1461.           break;
  1462.         case 'S':
  1463.           keep_going_flag = 0;
  1464.           break;
  1465.         case 't':
  1466.           touch_flag = 1;
  1467.           break;
  1468.         case 'v':
  1469.           print_version_flag = 1;
  1470.           break;
  1471.         case 'w':
  1472.           print_directory_flag = 1;
  1473.           break;
  1474.         default:
  1475.           fatal ("unknown switch: %c", sw[-1]);
  1476.         }
  1477.       if (keptflag != '\0')
  1478.     {
  1479.       argv[i][1] = keptflag;
  1480.       argv[i][2] = '\0';
  1481.     }
  1482.     }
  1483. }
  1484.  
  1485. static void
  1486. decode_env_switches (envar, len)
  1487.      char *envar;
  1488.      int len;
  1489. {
  1490.   struct macro *m;
  1491.   register char *args;
  1492.  
  1493.   m = lookup_macro (envar, len);
  1494.   if (m == 0 || *m->value == '\0')
  1495.     return;
  1496.  
  1497.   args = m->value;
  1498.   while (*args)
  1499.     switch (*args++)
  1500.       {
  1501.       case 'e':
  1502.     env_overrides = 1;
  1503.         break;
  1504.       case 'i':
  1505.     ignore_errors_flag = 1;
  1506.         break;
  1507.       case 'k':
  1508.     keep_going_flag = 1;
  1509.         break;
  1510.       case 'n':
  1511.     just_print_flag = 1;
  1512.         break;
  1513.       case 'q':
  1514.     question_flag = 1;
  1515.         break;
  1516.       case 'r':
  1517.     no_builtin_rules_flag = 1;
  1518.         break;
  1519.       case 's':
  1520.     silent_flag = 1;
  1521.         break;
  1522.       case 't':
  1523.     touch_flag = 1;
  1524.         break;
  1525.       case 'v':
  1526.     print_version_flag = 1;
  1527.     break;
  1528.       case 'w':
  1529.     print_directory_flag = 1;
  1530.     break;
  1531.       }
  1532.  
  1533.   return;
  1534. }
  1535.  
  1536. /* Implement macros.  */
  1537.  
  1538. /* Define macro named NAME with value VALUE.  VALUE is copied.
  1539.    LENGTH is the length of NAME, which does not
  1540.    need to be null-terminated.
  1541.    ORIGIN specifies the origin of the macro (makefile, command line
  1542.    or environment).
  1543.    If RECURSIVE is nonzero a flag is set in the macro saying
  1544.    that it should be recursively re-evaluated.  */
  1545.  
  1546. static struct macro *
  1547. define_macro (name, length, value, origin, recursive)
  1548.      char *name, *value;
  1549.      int length;
  1550.      enum macro_origin origin;
  1551.      char recursive;
  1552. {
  1553.   register struct macro *m;
  1554.   register int i;
  1555.   register int hashval = 0;
  1556.  
  1557.   for (i = 0; i < length; ++i)
  1558.     hashval += name[i];
  1559.   hashval %= MACRO_BUCKETS;
  1560.  
  1561.   for (m = macros[hashval]; m != 0; m = m->next)
  1562.     if (*m->name == *name
  1563.         && !strncmp (m->name + 1, name + 1, length - 1)
  1564.     && m->name[length] == '\0')
  1565.       break;
  1566.  
  1567.   if (m != 0)
  1568.     {
  1569.       /* A macro of this name is already defined.
  1570.      If the old definition is from a stronger source than this one,
  1571.      don't redefine.  */
  1572.       if ((int) origin >= (int) m->origin)
  1573.     {
  1574.       m->value = savestring (value, strlen (value));
  1575.       m->origin = origin;
  1576.       m->recursive = recursive;
  1577.     }
  1578.       return m;
  1579.     }
  1580.  
  1581.   /* Create a new macro definition and add to hash table.  */
  1582.  
  1583.   m = (struct macro *) xmalloc (sizeof (struct macro));
  1584.   m->name = savestring (name, length);
  1585.   m->value = savestring (value, strlen (value));
  1586.   m->origin = origin;
  1587.   m->recursive = recursive;
  1588.   m->expanding = 0;
  1589.   m->next = macros[hashval];
  1590.   return (macros[hashval] = m);
  1591. }
  1592.  
  1593. /* Lookup a macro whose name is a string starting at NAME
  1594.    and with LENGTH chars.  NAME need not be null-terminated.
  1595.    Returns address of the `struct macro' containing all info on the macro,
  1596.    or nil if no such macro is defined.  */
  1597.  
  1598. static struct macro *
  1599. lookup_macro (name, length)
  1600.      char *name;
  1601.      int length;
  1602. {
  1603.   register struct macro *m;
  1604.   register int i;
  1605.   register int hashval = 0;
  1606.  
  1607.   for (i = 0; i < length; ++i)
  1608.     hashval += name[i];
  1609.   hashval %= MACRO_BUCKETS;
  1610.  
  1611.   for (m = macros[hashval]; m != 0; m = m->next)
  1612.     if (*m->name == *name
  1613.         && !strncmp (m->name + 1, name + 1, length - 1)
  1614.     && m->name[length] == 0)
  1615.       return m;
  1616.  
  1617.   return 0;
  1618. }
  1619.  
  1620. /* Define the automatic macros, and record the addresses
  1621.    of their structures so we can change their values quickly.  */
  1622.  
  1623. static void
  1624. define_automatic_macros ()
  1625. {
  1626.   char mflags[100];    /* 100 is more than # of distinct option letters */
  1627.   register int i;
  1628.   register struct macro *m;
  1629.  
  1630.   star_macro = define_macro ("*", 1, "", o_override, 0);
  1631.   starF_macro = define_macro ("*F", 2, "", o_override, 0);
  1632.   starD_macro = define_macro ("*D", 2, "", o_override, 0);
  1633.   at_macro = define_macro ("@", 1, "", o_override, 0);
  1634.   atF_macro = define_macro ("@F", 2, "", o_override, 0);
  1635.   atD_macro = define_macro ("@D", 2, "", o_override, 0);
  1636.   less_macro = define_macro ("<", 1, "", o_override, 0);
  1637.   lessF_macro = define_macro ("<F", 2, "", o_override, 0);
  1638.   lessD_macro = define_macro ("<D", 2, "", o_override, 0);
  1639.   percent_macro = define_macro ("%", 1, "", o_override, 0);
  1640.   percentF_macro = define_macro ("%F", 2, "", o_override, 0);
  1641.   percentD_macro = define_macro ("%D", 2, "", o_override, 0);
  1642.   qmark_macro = define_macro ("?", 1, "", o_override, 0);
  1643.   caret_macro = define_macro ("^", 1, "", o_override, 0);
  1644.   dollar_slash_macro = define_macro ("$/", 1, "", o_override, 0);
  1645.  
  1646.   m = lookup_macro ("MAKELEVEL", 9);
  1647.   if (m && m->value)
  1648.     makelevel = atoi (m->value);
  1649.   else
  1650.     makelevel = 0;
  1651.  
  1652.   shell_macro = lookup_macro ("SHELL", 5);
  1653.   if (shell_macro == 0)
  1654.     shell_macro = define_macro ("SHELL", 5, "/bin/sh", o_file, 0);
  1655.  
  1656.   /* Don't let SHELL come from the environment
  1657.      if MAKELEVEL is 0.  Also, SHELL must not be empty.  */
  1658.   if (*shell_macro->value == '\0'
  1659.       || (shell_macro->origin == o_env && makelevel == 0))
  1660.     {
  1661.       shell_macro->origin = o_file;
  1662.       shell_macro->value = savestring ("/bin/sh", 7);
  1663.     }
  1664.  
  1665.   ifs_macro = lookup_macro ("IFS", 3);
  1666.  
  1667.   /* Define the built-in macro MAKEFLAGS to contain the command line switches.
  1668.      We can ignore here those switches that cause commands from the
  1669.      makefile not to be run.  */
  1670.  
  1671.   i = 0;
  1672.   mflags[i++] = '-';
  1673.   if (env_overrides) mflags[i++] = 'e';
  1674.   if (ignore_errors_flag) mflags[i++] = 'i';
  1675.   if (keep_going_flag) mflags[i++] = 'k';
  1676.   if (just_print_flag) mflags[i++] = 'n';
  1677.   if (question_flag) mflags[i++] = 'q';
  1678.   if (no_builtin_rules_flag) mflags[i++] = 'r';
  1679.   if (silent_flag) mflags[i++] = 's';
  1680.   if (touch_flag) mflags[i++] = 't';
  1681.   if (print_version_flag) mflags[i++] = 'v';
  1682.   if (print_directory_flag) mflags[i++] = 'w';
  1683.   mflags[i] = '\0';
  1684.   if (i == 1)
  1685.     mflags[0] = '\0';
  1686.   /* On Sun, value of MFLAGS starts with a `-'
  1687.      but value of MAKEFLAGS lacks the `-'.  Be compatible.  */
  1688.   define_macro ("MAKEFLAGS", 9, &mflags[1], o_env, 0);
  1689.   define_macro ("MFLAGS", 6, mflags, o_env, 0);
  1690. }
  1691.  
  1692. /* Try to interpret LINE (a null-terminated string)
  1693.    as a macro definition.  If it is one, define the macro and return 1.
  1694.    Otherwise return 0.
  1695.  
  1696.    ORIGIN be o_file, o_override, o_env, o_env_override, or o_command
  1697.    specifying that the macro definition comes from a makefile,
  1698.    an override directive, the environment with or without the -e switch,
  1699.    or the command line.
  1700.  
  1701.    A macro definition has the form "name = value" or "name := value".
  1702.    Any whitespace around the "=" or ":=" is removed.  The first
  1703.    form defines a macro that is recursively re-evaluated.  The second
  1704.    form defines a macro whose value is macro-expanded at the time
  1705.    of definition and then is evaluated only once at the time of expansion.  */
  1706.  
  1707. static int
  1708. try_macro_definition (line, origin)
  1709.      char *line;
  1710.      enum macro_origin origin;
  1711. {
  1712.   register int c;
  1713.   register char *p = line;
  1714.   register char *beg;
  1715.   register char *end;
  1716.   register int recursive;
  1717.  
  1718.   if (*p == '\t')
  1719.     return 0;
  1720.   while (1)
  1721.     {
  1722.       c = *p++;
  1723.       if (c == '\0' || c == '#')
  1724.     return 0;
  1725.       if (c == '=')
  1726.     {
  1727.       end = p - 1;
  1728.       recursive = 1;
  1729.       break;
  1730.     }
  1731.       else if (c == ':')
  1732.     if (*p == '=')
  1733.       {
  1734.         end = p - 1;
  1735.         c = *p++;
  1736.         recursive = 0;
  1737.         break;
  1738.       }
  1739.     else
  1740.       return 0;
  1741.     }
  1742.   beg = line;
  1743.   while (beg[0] == ' ' || beg[0] == '\t') beg++;
  1744.   while (end[-1] == ' ' || end[-1] == '\t') end--;
  1745.  
  1746.   while (*p == ' ' || *p == '\t') p++;
  1747.  
  1748.   define_macro (beg, end - beg, recursive ? p : macro_expand (p),
  1749.             origin, recursive);
  1750.  
  1751.   return 1;
  1752. }
  1753.  
  1754. /* Store into MACRO_BUFFER at O the result of scanning TEXT
  1755.    and replacing each occurrence of SUBST with REPLACE.
  1756.    TEXT is null-terminated.
  1757.    SLEN is the length of SUBST and RLEN is the length of REPLACE.
  1758.    If SUFFIX_ONLY is nonzero, the substitutions are only done
  1759.    at the ends of whitespace-delimited words.  */
  1760.  
  1761. static char *
  1762. subst_expand (o, text, subst, replace, slen, rlen, suffix_only)
  1763.      char *o;
  1764.      char *text;
  1765.      char *subst, *replace;
  1766.      int slen, rlen;
  1767.      int suffix_only;
  1768. {
  1769.   register char *t = text;
  1770.   register char *p;
  1771.  
  1772.  
  1773.   if (slen == 0)
  1774.     {
  1775.       /* The first occurance of "" in any string is its end.  */
  1776.       register int len = strlen (t);
  1777.       o = macro_buffer_output (o, t, len);
  1778.       t += len;
  1779.       if (rlen > 0)
  1780.     o = macro_buffer_output (o, replace, rlen);
  1781.     }
  1782.  
  1783.   while (p = sindex (t, 0, subst, slen))
  1784.     {
  1785.       /* Output everything before this occurance of the string to replace.  */
  1786.       if (p > t)
  1787.     o = macro_buffer_output (o, t, p - t);
  1788.       /* Advance T past the string to be replaced.  */
  1789.       t = p + slen;
  1790.  
  1791.       /* If we're substituting only at the end of whitespace-delimited
  1792.      words, check if we're at the end of one.  */
  1793.       if (suffix_only && (*t != '\0' && *t != ' ' && *t != '\t'))
  1794.     /* Struck out.  Output the rest of the string that is
  1795.        no longer to be replaced.  */
  1796.     o = macro_buffer_output (o, subst, slen);
  1797.       else if (rlen > 0)
  1798.     /* Output the replacement string.  */
  1799.     o = macro_buffer_output (o, replace, rlen);
  1800.     }
  1801.  
  1802.   /* Output everything left on the end.  */
  1803.   if (*t != '\0')
  1804.     o = macro_buffer_output (o, t, strlen (t));
  1805.  
  1806.   return o;
  1807. }
  1808.  
  1809. /* Store into MACRO_BUFFER at O the result of scanning TEXT
  1810.    and replacing strings matching PATTERN with REPLACE.  */
  1811.  
  1812. static char *
  1813. patsubst_expand (o, text, pattern, replace)
  1814.      char *o;
  1815.      char *text;
  1816.      register char *pattern, *replace;
  1817. {
  1818.   register char *pattern_percent = index (pattern, '%');
  1819.   register int pattern_prepercent_len, pattern_postpercent_len;
  1820.   register char *replace_percent = index (replace, '%');
  1821.   register int replace_prepercent_len, replace_postpercent_len;
  1822.   register char *t;
  1823.   int len;
  1824.   int doneany = 0;
  1825.  
  1826.  
  1827.   if (pattern_percent == 0)
  1828.     /* With no % in the pattern, this is just a simple substitution.  */
  1829.     return subst_expand (o, text, pattern, replace,
  1830.              strlen (pattern), strlen (replace), 0);
  1831.  
  1832.  
  1833.   /* We store the length of the part of the pattern before
  1834.      the % in PATTERN_PREPERCENT_LEN so we don't have to do
  1835.      the pointer arithmetic to compute it more than once.  */
  1836.   pattern_prepercent_len = pattern_percent - pattern;
  1837.   /* We store the length of the part of the pattern after
  1838.      the pattern in PATTERN_POSTPERCENT_LEN so we don't have
  1839.      to compute it more than once.  */
  1840.   pattern_postpercent_len = strlen (pattern_percent + 1);
  1841.  
  1842.   if (replace_percent == 0)
  1843.     /* We store the length of the replacement so we only
  1844.        need to compute it once.  */
  1845.     replace_prepercent_len = strlen (replace);
  1846.   else
  1847.     {
  1848.       /* We store the length of the part of the replacement before
  1849.      the % in REPLACE_PREPERCENT_LEN so we don't have to do
  1850.      the pointer arithmetic to compute it more than once.  */
  1851.       replace_prepercent_len = replace_percent - replace;
  1852.       /* We store the length of the part of the replacement after
  1853.      the pattern in REPLACE_POSTPERCENT_LEN so we don't have
  1854.      to compute it more than once.  */
  1855.       replace_postpercent_len = strlen (replace_percent + 1);
  1856.     }
  1857.  
  1858.  
  1859.   while (t = find_next_token (&text, &len))
  1860.     {
  1861.       int fail = 0;
  1862.  
  1863.       /* Is it big enough to match?  */
  1864.       if (len < pattern_prepercent_len + pattern_postpercent_len)
  1865.     fail = 1;
  1866.  
  1867.       /* Does the prefix match?  */
  1868.       if (!fail && pattern_prepercent_len > 0
  1869.       && (*t != *pattern
  1870.           || t[pattern_prepercent_len - 1] != pattern_percent[-1])
  1871.           || strncmp (t + 1, pattern + 1, pattern_prepercent_len - 1))
  1872.     fail = 1;
  1873.  
  1874.       /* Does the suffix match?  */
  1875.       if (!fail && pattern_postpercent_len > 0
  1876.       && (t[len - 1] != pattern_percent[pattern_postpercent_len]
  1877.           || t[len - pattern_postpercent_len] != pattern_percent[1]
  1878.           || strncmp (&t[len - pattern_postpercent_len],
  1879.               &pattern_percent[1], pattern_postpercent_len - 1)))
  1880.     fail = 1;
  1881.  
  1882.       if (fail)
  1883.     /* It didn't match.  Output the string.  */
  1884.     o = macro_buffer_output (o, t, len);
  1885.       else
  1886.     {
  1887.       /* It matched.  Output the replacement.  */
  1888.  
  1889.       /* Output the part of the replacement before the %.  */
  1890.       o = macro_buffer_output (o, replace, replace_prepercent_len);
  1891.  
  1892.       if (replace_percent != 0)
  1893.         {
  1894.           /* Output the part of the matched string that
  1895.          matched the % in the pattern.  */
  1896.           o = macro_buffer_output (o, t + pattern_prepercent_len,
  1897.                        len - (pattern_prepercent_len
  1898.                               + pattern_postpercent_len));
  1899.           /* Output the part of the replacement after the %.  */
  1900.           o = macro_buffer_output (o, replace_percent + 1,
  1901.                        replace_postpercent_len);
  1902.         }
  1903.     }
  1904.  
  1905.       /* Output a space, but not if the replacement is "".  */
  1906.       if (!(!fail && replace_percent == 0 && replace_postpercent_len == 0))
  1907.     {
  1908.       o = macro_buffer_output (o, " ", 1);
  1909.       doneany = 1;
  1910.     }
  1911.     }
  1912.   if (doneany)
  1913.     /* Kill the last space.  */
  1914.     --o;
  1915.  
  1916.   return o;
  1917. }
  1918.  
  1919. /* Handle macro-expansion-time functions such as $(dir foo/bar) ==> foo/  */
  1920.  
  1921. /* These enumeration constants distinguish the various expansion-time
  1922.    built-in functions.  */
  1923.  
  1924. enum function
  1925.   {
  1926.     function_subst,
  1927.     function_addsuffix,
  1928.     function_addprefix,
  1929.     function_dir,
  1930.     function_notdir,
  1931.     function_suffix,
  1932.     function_basename,
  1933.     function_wildcard,
  1934.     function_firstword,
  1935.     function_findstring,
  1936.     function_strip,
  1937.     function_join,
  1938.     function_patsubst,
  1939.     function_filter,
  1940.     function_filter_out,
  1941.     function_foreach,
  1942.     function_sort,
  1943.     function_invalid
  1944.   };
  1945.  
  1946. /* Greater than the length of any function name.  */
  1947. #define MAXFUNCTIONLEN 17
  1948.  
  1949. /* The function names and lengths of names, for looking them up.  */
  1950.  
  1951. struct { char *name; int len; enum function function; } function_table[] =
  1952.   {
  1953.     { "subst", 5, function_subst },
  1954.     { "addsuffix", 9, function_addsuffix },
  1955.     { "addprefix", 9, function_addprefix },
  1956.     { "dir", 3, function_dir },
  1957.     { "notdir", 6, function_notdir },
  1958.     { "suffix", 6, function_suffix },
  1959.     { "basename", 8, function_basename },
  1960.     { "wildcard", 8, function_wildcard },
  1961.     { "firstword", 9, function_firstword },
  1962.     { "findstring", 10, function_findstring },
  1963.     { "strip", 5, function_strip },
  1964.     { "join", 4, function_join },
  1965.     { "patsubst", 8, function_patsubst },
  1966.     { "filter", 6, function_filter },
  1967.     { "filter-out", 10, function_filter_out },
  1968.     { "foreach", 7, function_foreach },
  1969.     { "sort", 4, function_sort },
  1970.     { 0, 0, function_invalid }
  1971.   };
  1972.  
  1973. /* Return 1 if PATTERN matches WORD, 0 if not.  */
  1974. static int
  1975. pattern_matches (pattern, word)
  1976.      register char *pattern, *word;
  1977. {
  1978.   char *percent = index (pattern, '%');
  1979.   int len;
  1980.  
  1981.   if (percent == 0)
  1982.     return !strcmp (pattern, word);
  1983.  
  1984.   len = strlen (pattern + 1);
  1985.  
  1986.   if (strlen (word) < (percent - pattern) + len
  1987.       || strncmp (pattern, word, percent - pattern))
  1988.     return 0;
  1989.  
  1990.   return !strcmp (percent + 1, word + (strlen (word) - len));
  1991. }
  1992.  
  1993.  
  1994. /* Expand an argument for an expansion function.
  1995.    The text starting at STR and ending at END is macro-expanded
  1996.    into a null-terminated string that is returned as the value.
  1997.    This is done without clobbering `macro_buffer' or the current
  1998.    macro-expansion that is in progress.  */
  1999.  
  2000. static char *
  2001. expand_argument (str, end)
  2002.      char *str, *end;
  2003. {
  2004.   char *save_macro_buffer = macro_buffer;
  2005.   unsigned save_length = macro_buffer_length;
  2006.   char *tmp;
  2007.   char *value;
  2008.  
  2009.   macro_buffer = 0;
  2010.   tmp = savestring (str, end - str);
  2011.   value = macro_expand (tmp);
  2012.   free (tmp);
  2013.  
  2014.   macro_buffer = save_macro_buffer;
  2015.   macro_buffer_length = save_length;
  2016.  
  2017.   return value;
  2018. }
  2019.  
  2020.  
  2021. /* Perform the function specified by FUNCTION on the text at TEXT.
  2022.    END is points to the end of the argument text (exclusive).
  2023.    The output is written into MACRO_BUFFER starting at O.  */
  2024.  
  2025. static char *
  2026. expand_function (o, function, text, end)
  2027.      char *o;
  2028.      enum function function;
  2029.      char *text;
  2030.      char *end;
  2031. {
  2032.   char *p, *p2;
  2033.   int i;
  2034.   int doneany = 0;
  2035.  
  2036. /* Note this absorbs a semicolon and is safe to use in conditionals.  */
  2037. #define BADARGS(func)  \
  2038.   if (reading_filename)                        \
  2039.     fatal ("%s:%ld: Insufficient arguments to function `%s'",    \
  2040.        reading_filename, *reading_lineno_ptr, func);    \
  2041.   else fatal ("insufficient arguments to function `%s'", func)
  2042.  
  2043.   switch (function)
  2044.     {
  2045.     default:
  2046.       abort ();
  2047.       break;
  2048.       
  2049.     case function_sort:
  2050.       /* Expand the argument.  */
  2051.       text = expand_argument (text, end);
  2052.  
  2053.       {
  2054.     char **words = (char **) xmalloc (10 * sizeof (char *));
  2055.     int nwords = 10;
  2056.     register int wordi = 0;
  2057.  
  2058.     /* Chop TEXT into words and put them in WORDS.  */
  2059.     for (p = wstok(text); p != 0; p = wstok((char *) 0))
  2060.       {
  2061.         if (wordi >= nwords - 1)
  2062.           {
  2063.         nwords += 5;
  2064.         words = (char **) xrealloc (words, nwords * sizeof (char *));
  2065.           }
  2066.         words[wordi++] = savestring (p, strlen (p));
  2067.       }
  2068.     words[wordi] = 0;
  2069.  
  2070.     /* Now sort the list of words.  */
  2071.     qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
  2072.  
  2073.     /* Now write the sorted list.  */
  2074.     for (wordi = 0; words[wordi] != 0; ++wordi)
  2075.       {
  2076.         i = strlen (words[wordi]);
  2077.         if (words[wordi + 1] == 0 || strlen (words[wordi + 1]) != i
  2078.         || *words[wordi] != *words[wordi + 1]
  2079.         || strcmp (words[wordi], words[wordi + 1]))
  2080.           {
  2081.         o = macro_buffer_output (o, words[wordi], i);
  2082.         o = macro_buffer_output (o, " ", 1);
  2083.           }
  2084.         free (words[wordi]);
  2085.       }
  2086.     /* Kill the last space.  */
  2087.     --o;
  2088.  
  2089.     free (words);
  2090.       }
  2091.  
  2092.       free (text);
  2093.       break;
  2094.       
  2095.     case function_foreach:
  2096.       {
  2097.     /* Get three comma-separated arguments but
  2098.        expand only the first two.  */
  2099.     char *var, *list;
  2100.     register struct macro *m;
  2101.     char *saved_value;
  2102.     int saved_recursive;
  2103.     
  2104.     p = lindex (text, end, ',');
  2105.     if (p == 0)
  2106.       BADARGS ("foreach");
  2107.     var = expand_argument (text, p);
  2108.     ++p;
  2109.     p2 = lindex (p, end, ',');
  2110.     if (p2 == 0)
  2111.       BADARGS ("foreach");
  2112.     list = expand_argument (p, p2);
  2113.     ++p2;
  2114.     text = savestring (p2, end - p2);
  2115.  
  2116.     p2 = text + strlen (text);
  2117.     i = strlen (var);
  2118.     m = lookup_macro (var, i);
  2119.     if (m == 0)
  2120.       {
  2121.         saved_value = "";
  2122.         saved_recursive = 0;
  2123.         m = define_macro (var, i, saved_value, o_file, 0);
  2124.       }
  2125.     else
  2126.       {
  2127.         saved_value = m->value;
  2128.         saved_recursive = m->recursive;
  2129.         m->recursive = 0;
  2130.       }
  2131.     for (p = wstok(list); p != 0; p = wstok((char *) 0)) 
  2132.       {
  2133.         char *result;
  2134.         m->value = p;
  2135.         result = expand_argument (text, p2);
  2136.         o = macro_buffer_output (o, result, strlen (result));
  2137.       }
  2138.     m->value = saved_value;
  2139.     m->recursive = saved_recursive;
  2140.  
  2141.     free (var);
  2142.     free (list);
  2143.     free (text);
  2144.       }
  2145.       break;
  2146.  
  2147.     case function_filter:
  2148.     case function_filter_out:
  2149.       /* Get two comma-separated arguments and expand each one.  */
  2150.       p = lindex (text, end, ',');
  2151.       if (p == 0)
  2152.     BADARGS (function == function_filter ? "filter" : "filter-out");
  2153.       text = expand_argument (text, p);
  2154.       p = expand_argument (p + 1, end);
  2155.       
  2156.       /* Match the %-style pattern TEXT in P and output words
  2157.      that match (for filter) or ones that don't (for
  2158.      filter-out).  */
  2159.       if (function == function_filter_out)
  2160.     /* For filter-out it's simple: just use the patsubst
  2161.        function to replace matching words with nothing.  */
  2162.     o = patsubst_expand (o, p, text, "");
  2163.       else
  2164.     /* For filter we must do it ourselves.  */
  2165.     for (p2 = wstok (p); p2 != 0; p2 = wstok ((char *) 0))
  2166.       if (pattern_matches (text, p2))
  2167.         {
  2168.           o = macro_buffer_output (o, p2, strlen (p2));
  2169.           o = macro_buffer_output (o, " ", 1);
  2170.           /* Give us a little marker.  */
  2171.           p = 0;
  2172.         }
  2173.       if (p == 0)
  2174.     /* Kill the last space.  */
  2175.     --o;
  2176.       
  2177.       free (p);
  2178.       free (text);
  2179.       break;
  2180.       
  2181.     case function_patsubst:
  2182.       /* Get three comma-separated arguments and expand each one.  */
  2183.       p = lindex (text, end, ',');
  2184.       if (p == 0)
  2185.     BADARGS ("patsubst");
  2186.       p2 = lindex (p + 1, end, ',');
  2187.       if (p2 == 0)
  2188.     BADARGS ("patsubst");
  2189.       text = expand_argument (text, p);
  2190.       ++p;
  2191.       p = expand_argument (p, p2);
  2192.       ++p2;
  2193.       p2 = expand_argument (p2, end);
  2194.       
  2195.       o = patsubst_expand (o, p2, text, p);
  2196.       
  2197.       free (text);
  2198.       free (p);
  2199.       free (p2);
  2200.       break;
  2201.     case function_join:
  2202.       /* Get two comma-separated arguments and expand each one.  */
  2203.       p = lindex (text, end, ',');
  2204.       if (p == 0)
  2205.     BADARGS ("join");
  2206.       text = expand_argument (text, p);
  2207.       ++p;
  2208.       p = expand_argument (p, end);
  2209.       
  2210.       {
  2211.     /* Write each word of the first argument directly followed
  2212.        by the corresponding word of the second argument.
  2213.        If the two arguments have a different number of words,
  2214.        the excess words are just output separated by blanks.  */
  2215.     register char *tp, *pp;
  2216.     int tlen, plen;
  2217.     i = 0;
  2218.     do
  2219.       {
  2220.         tp = find_next_token (&text, &tlen);
  2221.         if (tp != 0)
  2222.           o = macro_buffer_output (o, tp, tlen);
  2223.         
  2224.         pp = find_next_token (&p, &plen);
  2225.         if (pp != 0)
  2226.           o = macro_buffer_output (o, pp, plen);
  2227.         
  2228.         if (tp != 0 || pp != 0)
  2229.           {
  2230.         o = macro_buffer_output (o, " ", 1);
  2231.         doneany = 1;
  2232.           }
  2233.       }
  2234.     while (tp != 0 || pp != 0);
  2235.     if (doneany)
  2236.       /* Kill the last blank.  */
  2237.       --o;
  2238.       }
  2239.       
  2240.       free (text);
  2241.       free (p);
  2242.       break;
  2243.       
  2244.     case function_strip:
  2245.       text = expand_argument (text, end);
  2246.       p = text;
  2247.       i = 0;
  2248.       while (*p)
  2249.     {
  2250.       while (*p == ' ' || *p == '\t' || *p == '\n')
  2251.         ++p;
  2252.       
  2253.       p2 = p;
  2254.       while (*p && *p != ' ' && *p != '\t' && *p != '\n')
  2255.         ++p;
  2256.       
  2257.       o = macro_buffer_output (o, p2, p - p2);
  2258.       o = macro_buffer_output (o, " ", 1);
  2259.       doneany = 1;
  2260.     }
  2261.       if (doneany)
  2262.     /* Kill the last space.  */
  2263.     --o;
  2264.       
  2265.       free (text);
  2266.       free (p);
  2267.       break;
  2268.       
  2269.     case function_wildcard:
  2270.       text = expand_argument (text, end);
  2271.       
  2272.       p = string_glob (text, 0);
  2273.       o = macro_buffer_output (o, p, strlen (p));
  2274.       
  2275.       free (text);
  2276.       break;
  2277.       
  2278.     case function_subst:
  2279.       /* Get three comma-separated arguments and expand each one.  */
  2280.       p = lindex (text, end, ',');
  2281.       if (p == 0)
  2282.     BADARGS ("subst");
  2283.       p2 = lindex (p + 1, end, ',');
  2284.       if (p2 == 0)
  2285.     BADARGS ("subst");
  2286.       text = expand_argument (text, p);
  2287.       ++p;
  2288.       p = expand_argument (p, p2);
  2289.       ++p2;
  2290.       p2 = expand_argument (p2, end);
  2291.       
  2292.       o = subst_expand (o, p2, text, p, strlen (text), strlen (p), 0);
  2293.       
  2294.       free (text);
  2295.       free (p);
  2296.       free (p2);
  2297.       break;
  2298.       
  2299.     case function_firstword:
  2300.       text = expand_argument (text, end);
  2301.       /* Find the first word in TEXT.  */
  2302.       
  2303.       p = wstok (text);
  2304.       o = macro_buffer_output (o, p, strlen (p));
  2305.       
  2306.       free (text);
  2307.       break;
  2308.       
  2309.     case function_findstring:
  2310.       /* Get two comma-separated arguments and expand each one.  */
  2311.       p = lindex (text, end, ',');
  2312.       if (p == 0)
  2313.     BADARGS ("findstring");
  2314.       text = expand_argument (text, p);
  2315.       ++p;
  2316.       p = expand_argument (p, end);
  2317.       
  2318.       /* Find the first occurence of the first string in the second.  */
  2319.       i = strlen (text);
  2320.       if (sindex (p, 0, text, i) != 0)
  2321.     o = macro_buffer_output (o, text, i);
  2322.       
  2323.       free (p);
  2324.       free (text);
  2325.       break;
  2326.       
  2327.     case function_addsuffix:
  2328.     case function_addprefix:
  2329.       /* Get two comma-separated arguments and expand each one.  */
  2330.       p2 = lindex (text, end, ',');
  2331.       if (p2 == 0)
  2332.     BADARGS (function == function_addsuffix ? "addsuffix" : "addprefix");
  2333.       text = expand_argument (text, p2);
  2334.       i = strlen (text);
  2335.       ++p2;
  2336.       p2 = expand_argument (p2, end);
  2337.       
  2338.       for (p = wstok (p2); p != 0; p = wstok ((char *) 0))
  2339.     {
  2340.       if (function == function_addprefix)
  2341.         o = macro_buffer_output (o, text, i);
  2342.       o = macro_buffer_output (o, p, strlen (p));
  2343.       if (function == function_addsuffix)
  2344.         o = macro_buffer_output (o, text, i);
  2345.       o = macro_buffer_output (o, " ", 1);
  2346.       doneany = 1;
  2347.     }
  2348.       if (doneany)
  2349.     /* Kill last space.  */
  2350.     --o;
  2351.       
  2352.       free (p2);
  2353.       free (text);
  2354.       break;
  2355.       
  2356.     case function_dir:
  2357.     case function_basename:
  2358.       text = expand_argument (text, end);
  2359.       for (p2 = wstok (text); p2; p2 = wstok ((char *) 0))
  2360.     {
  2361. #ifdef atarist
  2362.       p = rindex (p2, function == function_dir ? '\\' : '.');
  2363. #else
  2364.       p = rindex (p2, function == function_dir ? '/' : '.');
  2365. #endif
  2366.       if (p != 0)
  2367.         {
  2368.           if (function == function_dir)
  2369.         ++p;
  2370.           o = macro_buffer_output (o, p2, p - p2);
  2371.         }
  2372.       else if (function == function_dir)
  2373.         o = macro_buffer_output (o, "./", 2);
  2374.       else  /* The entire name is the basename.  */
  2375.         o = macro_buffer_output (o, p2, strlen (p2));
  2376.       o = macro_buffer_output (o, " ", 1);
  2377.       doneany = 1;
  2378.     }
  2379.       if (doneany)
  2380.     /* Kill last space.  */
  2381.     --o;
  2382.       
  2383.       free (text);
  2384.       break;
  2385.       
  2386.     case function_notdir:
  2387.     case function_suffix:
  2388.       text = expand_argument (text, end);
  2389.       for (p2 = wstok (text); p2; p2 = wstok ((char *) 0))
  2390.     {
  2391. #ifdef atarist
  2392.       p = rindex (p2, function == function_notdir ? '\\' : '.');
  2393. #else
  2394.       p = rindex (p2, function == function_notdir ? '/' : '.');
  2395. #endif
  2396.       if (p != 0)
  2397.         {
  2398.           ++p;
  2399.           o = macro_buffer_output (o, p, strlen (p));
  2400.         }
  2401.       else if (function == function_notdir)
  2402.         o = macro_buffer_output (o, p2, strlen (p2));
  2403.       if ((p && *p) || function == function_notdir)
  2404.         o = macro_buffer_output (o, " ", 1);
  2405.       doneany = 1;
  2406.     }
  2407.       if (doneany)
  2408.     /* Kill last space.  */
  2409.     --o;
  2410.       free (text);
  2411.       break;
  2412.     }
  2413.  
  2414.   return o;
  2415. }
  2416.  
  2417. /* Scan LINE for macro references and expansion-function calls.
  2418.    Build in `macro_buffer' the result of expanding those references and calls.
  2419.    Return the address of the resulting string, which is null-terminated
  2420.    and is valid only until the next time this function is called.  */
  2421.  
  2422. static char *
  2423. macro_expand (line)
  2424.      register char *line;
  2425. {
  2426.   register struct macro *m;
  2427.   register char *p, *o, *p1;
  2428.  
  2429.  
  2430.   /* If we don't have a macro output buffer yet, get one.
  2431.      The same buffer is reused each time macro_expand is called,
  2432.      and made bigger whenever necessary.  */
  2433.  
  2434.   if (macro_buffer == 0)
  2435.     {
  2436.       macro_buffer_length = 200;
  2437.       macro_buffer = (char *) xmalloc (macro_buffer_length);
  2438.     }
  2439.  
  2440.   p = line;
  2441.   o = macro_buffer;
  2442.   *o = '\0';
  2443.  
  2444.   while (1)
  2445.     {
  2446.       /* Copy all following uninteresting chars all at once to the
  2447.          macro output buffer, and skip them.  Uninteresting chars end
  2448.      at the next $ or the end of the input.  */
  2449.  
  2450.       p1 = index (p, '$');
  2451.       o = macro_buffer_output (o, p, p1 ? p1 - p : strlen (p) + 1);
  2452.  
  2453.       if (p1 == 0)
  2454.     break;
  2455.       p = p1 + 1;
  2456.  
  2457.       /* Dispatch on the char that follows the $.  */
  2458.  
  2459.       switch (*p)
  2460.     {
  2461.     case '$':
  2462.       /* $$ seen means output one $ to the output buffer.  */
  2463.  
  2464.       o = macro_buffer_output (o, p, 1);
  2465.       break;
  2466.  
  2467.     case '(':
  2468.     case '{':
  2469.       /* $(...) or ${...} is the general case of substitution.  */
  2470.  
  2471.       {
  2472.         char openparen = *p;
  2473.         char closeparen = (openparen == '(') ? ')' : '}';
  2474.         register char *beg = p + 1;
  2475.         char *end;
  2476.         register int code;
  2477.         int maxlen;
  2478.  
  2479.         /* Is there a macro reference inside the parens or braces?
  2480.            If so, expand it before doing anything else.  */
  2481.  
  2482.         p1 = index (beg, '$');
  2483.         if (p1 != 0)
  2484.           {
  2485.         /* BEG now points past the opening paren or brace.
  2486.            Count parens or braces until it is matched.  */
  2487.         int count = 0;
  2488.         for (p = beg; *p != '\0'; ++p)
  2489.           {
  2490.             if (*p == openparen)
  2491.               ++count;
  2492.             else if (*p == closeparen && --count < 0)
  2493.               break;
  2494.           }
  2495.         if (count >= 0)
  2496.           /* There were insufficient closing parens or braces
  2497.              to terminate the macro reference.  */
  2498.           return macro_buffer;
  2499.         else
  2500.           {
  2501.             char *name = expand_argument (beg, p);
  2502.             p1 = concat ("$(", name, ")");
  2503.             free (name);
  2504.             name = expand_argument (p1, p1 + strlen (p1));
  2505.             o = macro_buffer_output (o, name, strlen (name));
  2506.             free (name);
  2507.           }
  2508.         break;
  2509.           }
  2510.  
  2511.         /* First, see if this is a reference to a built-in function.
  2512.            That is so if the text inside the parens starts with
  2513.            the name of a function ended by a space or tab.  */
  2514.  
  2515.         p1 = lindex (beg, beg + MAXFUNCTIONLEN, '\0');
  2516.         maxlen = p1 ? p1 - beg : MAXFUNCTIONLEN;
  2517.  
  2518.         for (code = 0; function_table[code].name; ++code)
  2519.           {
  2520.         if (maxlen < function_table[code].len)
  2521.           continue;
  2522.         p1 = beg + function_table[code].len;
  2523.         if ((*p1 == ' ' || *p1 == '\t')
  2524.             && !strncmp (function_table[code].name, beg,
  2525.                  function_table[code].len))
  2526.           break;
  2527.           }
  2528.         if (function_table[code].name)
  2529.           {
  2530.         /* We have found a call to an expansion-time function.
  2531.            Find the end of the arguments, and do the function.  */
  2532.  
  2533.         int count = 0;
  2534.         char *argbeg;
  2535.  
  2536.         /* Space after function name isn't part of the args.  */
  2537.         p = p1;
  2538.         while (*p == ' ' || *p == '\t')
  2539.           ++p;
  2540.         argbeg = p;
  2541.  
  2542.         /* Count nested use of whichever kind of parens we use,
  2543.            so that nested calls and macro refs work.  */
  2544.  
  2545.         for (; *p; ++p)
  2546.           {
  2547.             if (*p == openparen)
  2548.               ++count;
  2549.             else if (*p == closeparen && --count < 0)
  2550.               break;
  2551.           }
  2552.  
  2553.         /* We found the end; expand the function call.  */
  2554.  
  2555.         o = expand_function (o, function_table[code].function,
  2556.                      argbeg, p);
  2557.         break;
  2558.           }
  2559.  
  2560.         /* This is not a reference to a built-in function.
  2561.            There are several things it could be.  In any case,
  2562.            find the end of it, which is the first close-paren
  2563.            of the appropriate type.  (We do not count them.)  */
  2564.  
  2565.         end = index (beg, closeparen);
  2566.         if (end == 0)
  2567.           /* There was no ending ) or } !!
  2568.          Swallow the line (and screw the hook and sinker).  */
  2569.           return (macro_buffer);
  2570.  
  2571.         /* This is not a reference to a built-in function.  Is it
  2572.            an old-fashioned substitution spec, $(FOO:BAR=UGH)?  */
  2573.  
  2574.         if ((p = lindex (beg, end, ':')) && (p1 = lindex (p, end, '=')))
  2575.           {
  2576.         int slen = p1 - p - 1;
  2577.         int rlen = end - p1 - 1;
  2578.         m = lookup_macro (beg, p - beg);
  2579.         if (m != 0 && *m->value != '\0')
  2580.           o = subst_expand (o, m->value, p+1, p1+1, slen, rlen, 1);
  2581.           }
  2582.  
  2583.         /* No, this must be an ordinary macro reference.  */
  2584.         else
  2585.           {
  2586.         /* Look up the value of the macro.  */
  2587.         m = lookup_macro (beg, end - beg);
  2588.  
  2589.         if (m != 0 && *m->value != '\0')
  2590.           if (m->expanding)
  2591.             fatal ("Recursive variable `%s' references\
  2592. itself (eventually)",
  2593.                m->name);
  2594.           else if (m->recursive)
  2595.             {
  2596.               /* Re-expand the macro value.  */
  2597.               m->expanding = 1;
  2598.               p = expand_argument (m->value,
  2599.                            m->value + strlen (m->value));
  2600.               m->expanding = 0;
  2601.  
  2602.               /* Output the re-expanded value.  */
  2603.               o = macro_buffer_output (o, p, strlen (p));
  2604.             }
  2605.           else
  2606.             o = macro_buffer_output (o, m->value, strlen (m->value));
  2607.           }
  2608.  
  2609.         /* Advance p past the macro reference to resume scan.  */
  2610.         p = end;
  2611.       }
  2612.       break;
  2613.  
  2614.     case '\0':
  2615.     case '\t':
  2616.     case ' ':
  2617.       break;
  2618.  
  2619.     default:
  2620.       /* A $ followed by a random char is a macro reference:
  2621.          $a is equivalent to $(a).  */
  2622.  
  2623.       m = lookup_macro (p, 1);
  2624.       if (m != 0 && *m->value != '\0')
  2625.         if (m->expanding)
  2626.           fatal ("Recursive variable `%s' references itself (eventually)",
  2627.              m->name);
  2628.         else if (m->recursive)
  2629.           {
  2630.         /* Re-expand the macro value.  */
  2631.         m->expanding = 1;
  2632.         p1 = expand_argument (m->value,
  2633.                       m->value + strlen (m->value));
  2634.         m->expanding = 0;
  2635.         
  2636.         /* Output the re-expanded value.  */
  2637.         o = macro_buffer_output (o, p1, strlen (p1));
  2638.           }
  2639.         else
  2640.           o = macro_buffer_output (o, m->value, strlen (m->value));
  2641.  
  2642.       break;
  2643.     }      
  2644.       ++p;
  2645.     }
  2646.   return macro_buffer;
  2647. }
  2648.  
  2649. /* Subroutine of macro_expand and friends:
  2650.    The text to add is LENGTH chars starting at STRING to the macro_buffer.
  2651.    The text is added to the buffer at PTR, and the updated pointer into
  2652.    the buffer is returned as the value.  Thus, the value returned by
  2653.    each call to macro_buffer_output should be the first argument to
  2654.    the following call.  */
  2655.  
  2656. static char *
  2657. macro_buffer_output (ptr, string, length)
  2658.      char *ptr, *string;
  2659.      int length;
  2660. {
  2661.   register int newlen = length + (ptr - macro_buffer);
  2662.   register char *new;
  2663.  
  2664.   if (newlen > macro_buffer_length)
  2665.     {
  2666.       macro_buffer_length = max (2 * macro_buffer_length, newlen + 100);
  2667.       new = (char *) xrealloc (macro_buffer, macro_buffer_length);
  2668.       ptr += new - macro_buffer;
  2669.       macro_buffer = new;
  2670.     }
  2671.  
  2672.   bcopy (string, ptr, (int) length);
  2673.   return (ptr + length);
  2674. }
  2675.  
  2676. /* Access the hash table of all file records.
  2677.    lookup_file  given a name, return the struct file * for that name,
  2678.            or nil if there is none.
  2679.    enter_file   similar, but create one if there is none.  */
  2680.  
  2681. static struct file *
  2682. lookup_file (name)
  2683.      char *name;
  2684. {
  2685.   register struct file *f;
  2686.   register char *n;
  2687.   register int hashval = 0;
  2688.  
  2689. #ifdef atarist
  2690.   while (name[0] == '.' && name[1] == '\\' && name[2])
  2691. #else
  2692.   while (name[0] == '.' && name[1] == '/' && name[2])
  2693. #endif
  2694.     name += 2;
  2695.  
  2696.   if (*name == '\0')
  2697.     abort ();
  2698.  
  2699.   for (n = name; *n; ++n)
  2700. #ifdef case_insensitive
  2701.     hashval += char_upcase(*n);
  2702. #else
  2703.     hashval += *n;
  2704. #endif
  2705.   hashval %= FILE_BUCKETS;
  2706.  
  2707.   for (f = files[hashval]; f != 0; f = f->next)
  2708.     if (streq (f->name, name))
  2709.       return (f);
  2710.   return (0);
  2711. }
  2712.  
  2713. static struct file *
  2714. enter_file (name)
  2715.      char *name;
  2716. {
  2717.   register struct file *f, *lastf;
  2718.   register char *n;
  2719.   register int hashval = 0;
  2720.  
  2721. #ifdef atarist
  2722.   while (name[0] == '.' && name[1] == '\\' && name[2])
  2723. #else
  2724.   while (name[0] == '.' && name[1] == '/' && name[2])
  2725. #endif
  2726.     name += 2;
  2727.  
  2728.   if (*name == '\0')
  2729.     abort ();
  2730.  
  2731.   for (n = name; *n; ++n)
  2732. #ifdef case_insensitive
  2733.     hashval += char_upcase(*n);
  2734. #else
  2735.     hashval += *n;
  2736. #endif
  2737.   hashval %= FILE_BUCKETS;
  2738.  
  2739.   for (lastf = f = files[hashval]; f != 0; lastf = f, f = f->next)
  2740.     if (streq (f->name, name))
  2741.       break;
  2742.  
  2743.   if (f != 0)
  2744.     if (f->double_colon)
  2745.       {
  2746.     /* If there is a double-colon entry for NAME, we want to
  2747.        add another entry, but make it so the original one,
  2748.        now pointed to by F, will always be the first found.  */
  2749.     /* Remove F from the chain.  */
  2750.     if (f == lastf)
  2751.       /* If F and LASTF are the same, we are at the beginning
  2752.          of the chain and must change the head pointer.  */
  2753.       files[hashval] = f->next;
  2754.     else
  2755.       lastf->next = f->next;
  2756.       }
  2757.     else
  2758.       return f;
  2759.  
  2760.   lastf = (struct file *) xmalloc (sizeof (struct file));
  2761.   bzero ((char *) lastf, sizeof (struct file));
  2762.   lastf->name = name;
  2763.   lastf->update_status = -1;
  2764.  
  2765.   lastf->next = files[hashval];
  2766.   files[hashval] = lastf;
  2767.   if (f != 0)
  2768.     {
  2769.       /* Put F in front of the newly created LASTF.  */
  2770.       f->next = files[hashval];
  2771.       files[hashval] = f;
  2772.     }
  2773.  
  2774.   return lastf;
  2775. }
  2776.  
  2777. /* Print version information.
  2778.    This prints:
  2779.  
  2780.      GNU Make version X.Y (Rel), by Richard Stallman and Roland McGrath.
  2781.      Copyright (C) 1988 Free Software Foundation, Inc.
  2782.      This is free software; see the source file for copying conditions.
  2783.      There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
  2784.      PARTICULAR PURPOSE.
  2785.  
  2786.    where X.Y is the second word of `$Revision: 2.0 $' and Rel is
  2787.    the second word of `$State: Rel $'.  */
  2788.  
  2789. static void
  2790. print_version ()
  2791. {
  2792.   char *revision = &"$Revision: 2.0 $"[11];
  2793.   char *state = &"$State: Rel $"[8];
  2794.   int rlen, slen;
  2795.   
  2796.  
  2797.   /* If this was compiled from a checked-out and locked version
  2798.      of the source, the RCS keywords have no values.  */
  2799.   if (revision[-2] == '$' || state[-2] == '$')
  2800.     {
  2801.       revision = "(New)";
  2802.       state = "in progess";
  2803.       rlen = 5;
  2804.       slen = 10;
  2805.     }
  2806.   else
  2807.     {
  2808.       rlen = index (revision, ' ') - revision;
  2809.       slen = index (state, ' ') - state;
  2810.     }
  2811.   
  2812.  
  2813.   printf ("GNU Make version %.*s (%.*s), ", rlen, revision, slen, state);
  2814.  
  2815.   puts ("by Richard Stallman and Roland McGrath.\n\
  2816. Copyright (C) 1988 Free Software Foundation, Inc.\n\
  2817. This is free software; see the source file for copying conditions.\n\
  2818. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
  2819. PARTICULAR PURPOSE.\n");
  2820.  
  2821.   /* Flush stdout so the user doesn't have to wait to see the
  2822.      version information while things are thought about.  */
  2823.   fflush (stdout);
  2824. }
  2825.  
  2826. /* Print the contents of the files and macros hash tables.  */
  2827.  
  2828. static void
  2829. print_data_base ()
  2830. {
  2831.   register struct macro *m;
  2832.   register struct file *f;
  2833.   register struct dep *d;
  2834.   register struct rule *r;
  2835.   register struct dirdata *dir;
  2836.   register int i, j, k;
  2837.  
  2838.   print_version ();
  2839.  
  2840.   puts ("\nMacros\n");
  2841.  
  2842.   j = 0;
  2843.   for (i = 0; i < MACRO_BUCKETS; ++i)
  2844.     for (m = macros[i]; m != 0; m = m->next)
  2845.       {
  2846.     ++j;
  2847.     printf ("%s = %s\n", m->name, m->value);
  2848.       }
  2849.  
  2850.   printf ("\n%d macros in %d hash buckets, average %f macros per bucket.\n",
  2851.       j, MACRO_BUCKETS, ((float) j) / MACRO_BUCKETS);
  2852.  
  2853.   puts ("\nImplicit rules\n");
  2854.  
  2855.   j = k = 0;
  2856.   for (r = pattern_rules; r != 0; r = r->next)
  2857.     {
  2858.       ++j;
  2859.       printf ("%s:", r->name);
  2860.       if (r->terminal)
  2861.     {
  2862.       ++k;
  2863.       puts ("   (terminal)");
  2864.     }
  2865.       else
  2866.     putchar ('\n');
  2867.       for (d = r->deps; d != 0; d = d->next)
  2868.     printf (" depends on %s\n", dep_name (d));
  2869.       if (r->cmds)
  2870.     {
  2871.       struct commands *c = r->cmds;
  2872.       if (c->filename)
  2873.         printf (" commands to execute (from `%s', line %ld):\n  %s",
  2874.             c->filename, c->lineno, c->commands);
  2875.       else
  2876.         printf (" commands to execute:\n  %s\n", c->commands);
  2877.     }
  2878.     }
  2879.  
  2880.   printf ("\n%d implicit rules, %d (%f%%) terminal.\n", j, k, 100 * k / j);
  2881.  
  2882.   puts ("\nDirectories\n");
  2883.  
  2884.   j = k = 0;
  2885.   for (i = 0; i < DIR_HASH_SIZE; ++i)
  2886.     for (dir = dir_hash_table[i]; dir != 0; dir = dir->next)
  2887.       {
  2888.     ++k;
  2889.     if (dir->name[0] == '.' && dir->name[1] == '\0')
  2890.       {
  2891.         ++j;
  2892.         puts (dir->dir);
  2893.       }
  2894.       }
  2895.  
  2896.   printf ("\n%d directories with a total of %d files in %d hash buckets,\n",
  2897.        j, k, DIR_HASH_SIZE);
  2898.   printf ("average of %f files per bucket.\n", ((float) k) / DIR_HASH_SIZE);
  2899.  
  2900.   puts ("\nFiles\n");
  2901.  
  2902.   j = 0;
  2903.   for (i = 0; i < FILE_BUCKETS; ++i)
  2904.     for (f = files[i]; f != 0; f = f->next)
  2905.       {
  2906.     ++j;
  2907.     fputs (f->name, stdout);
  2908.     if (f->is_target)
  2909.       putchar (':');
  2910.     if (f->double_colon)
  2911.       putchar (':');
  2912.     if (f->stem != 0)
  2913.       printf ("   (implicit rule stem `%s')", f->stem);
  2914.     putchar ('\n');
  2915.     for (d = f->deps; d != 0; d = d->next)
  2916.       printf (" depends on %s\n", dep_name (d));
  2917.     if (f->cmds)
  2918.       {
  2919.         struct commands *c = f->cmds;
  2920.         if (c->filename)
  2921.           printf (" commands to execute (from `%s', line %ld):\n  %s",
  2922.               c->filename, c->lineno, c->commands);
  2923.         else
  2924.           printf (" commands to execute:\n  %s\n", c->commands);
  2925.       }
  2926.       }
  2927.  
  2928.   printf ("\n%d files in %d hash buckets, average %f files per bucket.\n",
  2929.       j, FILE_BUCKETS, ((float) j) / FILE_BUCKETS);
  2930.  
  2931.   puts ("\nDone");
  2932.   fflush (stdout);
  2933. }
  2934.  
  2935. void read_makefile (), record_files ();
  2936.  
  2937. /* Look at out command args to determine the names of the makefiles
  2938.    and read all those files, adding their macro definitions and rules
  2939.    to the macro and file hash tables.  */
  2940.  
  2941. static void
  2942. read_all_makefiles (argc, argv)
  2943.      int argc;
  2944.      char **argv;
  2945. {
  2946.   struct macro *m;
  2947.   register int i;
  2948.   int num_makefiles = 0;
  2949.  
  2950.   /* If there's a non-null macro MAKEFILES,
  2951.      its value a list of files to read first thing.
  2952.      But don't let it prevent reading the default makefiles
  2953.      and don't let the default goal come from there.  */
  2954.  
  2955.   m = lookup_macro ("MAKEFILES", 9);
  2956.   if (m && *m->value)
  2957.     {
  2958.       char *rest = m->value;
  2959.       char *name;
  2960.       int length;
  2961.       /* Set NAME to start of next token and LENGTH to its length.
  2962.      REST is updated for finding remaining tokens.  */
  2963.       while (name = find_next_token (&rest, &length))
  2964.     {
  2965.       name = savestring (name, length);
  2966.       if (file_exists_p (name))
  2967.         read_makefile (name, 1, 0);
  2968.       else
  2969.         free (name);
  2970.     }
  2971.     }
  2972.  
  2973.   /* Read makefiles specified with -f switches.  */
  2974.  
  2975.   for (i = 1; i < argc; i++)
  2976.     if (!strcmp (argv[i], "-f"))
  2977.       {
  2978.     ++i;
  2979.     if (i >= argc)
  2980.       fatal ("no description argument after -f command option");
  2981.     read_makefile (argv[i], 0, 2);
  2982.     ++num_makefiles;
  2983.       }
  2984.  
  2985.   /* If there were no -f switches, try the default names.  */
  2986.  
  2987.   if (num_makefiles == 0)
  2988.     {
  2989.       if (file_exists_p ("makefile"))
  2990.     read_makefile ("makefile", 0, 2);
  2991.       else if (file_exists_p ("Makefile"))
  2992.     read_makefile ("Makefile", 0, 2);
  2993.       else if (argc <= 1)
  2994.     fatal ("no target arguments or description file");
  2995.     }
  2996. }
  2997.  
  2998. /* Read file FILENAME as a makefile and add its contents to the data base.
  2999.    NODEFAULT means don't take the default goal target from this makefile.
  3000.    ERRORLEVEL determines the behavior if the file is not found.
  3001.    If it is <= 0, nothing happens.  If it is 1, a message is issued.
  3002.    If it is > 1, a message is issued and the program exits.  */
  3003.  
  3004. static void
  3005. read_makefile (filename, nodefault, errorlevel)
  3006.      char *filename;
  3007.      int nodefault;
  3008.      int errorlevel;
  3009. {
  3010.   register FILE *infile;
  3011.   struct linebuffer lb;
  3012.   int commands_len = 200;
  3013.   char *commands = (char *) xmalloc (200);
  3014.   int commands_idx = 0;
  3015.   long commands_started;
  3016.   register char *p;
  3017.   char *p2;
  3018.   int ignoring = 0;
  3019.  
  3020.   struct nameseq *filenames = 0;
  3021.   struct dep *deps = 0;
  3022.   long lineno = 1;
  3023.   long nlines = 0;
  3024.   int two_colon;
  3025.   char *cmdleft;
  3026.   char *t;
  3027.   char *pattern = 0;
  3028.   
  3029. #ifdef    lint    /* Suppress `used before set' messages.  */
  3030.   two_colon = 0;
  3031. #endif
  3032.  
  3033.   /* First, get a stream to read.  */
  3034.  
  3035.   if (!strcmp (filename, "-"))
  3036.     infile = stdin;
  3037.   else
  3038.     infile = fopen (filename, "r");
  3039.  
  3040. #ifdef atarist
  3041.   if (infile == 0 && nodefault && *filename != '\\' && include_directories)
  3042. #else
  3043.   if (infile == 0 && nodefault && *filename != '/' && include_directories)
  3044. #endif
  3045.     {
  3046.       register int i;
  3047.       char *name = (char *) alloca (max_incl_len + 1 + strlen (filename) + 1);
  3048.       for (i = 0; include_directories[i] != 0; ++i)
  3049.     {
  3050. #ifdef atarist
  3051.       sprintf (name, "%s\\%s", include_directories[i], filename);
  3052. #else
  3053.       sprintf (name, "%s/%s", include_directories[i], filename);
  3054. #endif
  3055.       infile = fopen (name, "r");
  3056.       if (infile != 0)
  3057.         {
  3058.           filename = name;
  3059.           break;
  3060.         }
  3061.     }
  3062.     }
  3063.  
  3064.   /* If file can't be found at all, either ignore it or give up entirely.  */
  3065.  
  3066.   if (infile == 0)
  3067.     {
  3068.       if (errorlevel > 1)
  3069.     pfatal_with_name (filename);
  3070.       else if (errorlevel > 0)
  3071.     perror_with_name ("", filename);
  3072.       return;
  3073.     }
  3074.  
  3075.   reading_filename = filename;
  3076.   reading_lineno_ptr = &lineno;
  3077.  
  3078.   /* Loop over lines in the file.
  3079.      The strategy is to accumulate target names in FILENAMES,
  3080.      dependencies in DEPS and commands in COMMANDS.
  3081.      These are used to define a rule
  3082.      when the start of the next rule (or eof) is encountered.  */
  3083.  
  3084.   initbuffer (&lb);
  3085.  
  3086.   while (!feof (infile))
  3087.     {
  3088.       lineno += nlines;
  3089.       nlines = readline (&lb, infile, filename, lineno);
  3090.  
  3091.       p = lb.buffer;
  3092.  
  3093. #define    word1eq(s, l)     ((p[l] == '\0' || p[l] == ' ' || p[l] == '\t') && \
  3094.              !strncmp (s, p, l))
  3095.  
  3096.       while (*p == ' ' || *p == '\t')
  3097.     ++p;
  3098.       if (*p == '\0')
  3099.     continue;
  3100.       p = lb.buffer;
  3101.       if (word1eq ("ifdef", 5) || word1eq ("ifndef", 6)
  3102.       || word1eq ("ifeq", 4) || word1eq ("ifneq", 5)
  3103.       || word1eq ("else", 4) || word1eq ("endif", 5))
  3104.     {
  3105.       int i = conditional_line (p, filename, lineno);
  3106.       if (i >= 0)
  3107.         {
  3108.           ignoring = i;
  3109.           continue;
  3110.         }
  3111.       else
  3112.         fatal ("%s:%ld: invalid syntax in conditional", filename, lineno);
  3113.     }
  3114.       if (ignoring)
  3115.     continue;
  3116.       else if (word1eq ("define", 6))
  3117.     {
  3118.       p += 6;
  3119.       p2 = next_token (p);
  3120.       p = end_of_token (p2);
  3121.       lineno = do_define (&lb, savestring (p2, p - p2),
  3122.                   lineno, infile, filename);
  3123.       continue;
  3124.     }
  3125.       else if (word1eq ("endef", 5))
  3126.     fatal ("%s:%ld: extraneous `endef'", filename, lineno);
  3127.       else if (word1eq ("override", 8))
  3128.     {
  3129.       p += 8;
  3130.       p2 = next_token (p);
  3131.       if (p2 == 0 || !try_macro_definition (p2, o_override))
  3132.         fatal ("%s:%ld: Empty `override' directive", filename, lineno);
  3133.     }
  3134.       else if (word1eq ("include", 7))
  3135.     {
  3136.       /* We have found an `include' line specifying a nested
  3137.          makefile to be read at this point.  */
  3138.       p += 8;
  3139.       p2 = next_token (p);
  3140.       if (p2 == 0)
  3141.         fatal ("%s:%ld: no filename for `include'", filename, lineno);
  3142.       p = end_of_token (p2);
  3143.       p = savestring (p2, p - p2);
  3144.       read_makefile (p, 1, 1);
  3145.       continue;
  3146.     }
  3147.       else if (word1eq ("vpath", 5))
  3148.     {
  3149.       char *pattern;
  3150.       p += 5;
  3151.       p2 = macro_expand (p);
  3152.       p = next_token (p2);
  3153.       if (p != 0)
  3154.         {
  3155.         p2 = end_of_token (p);
  3156.         pattern = savestring (p, p2 - p);
  3157.         p = next_token (p2);
  3158.         if (p != 0)
  3159.           {
  3160.         p2 = end_of_token (p);
  3161.         p = savestring (p, p2 - p);
  3162.           }
  3163.           /* No searchpath means remove all previous selective VPATH's
  3164.          with the same pattern.  */
  3165.         }
  3166.       else
  3167.         /* No pattern means remove all previous selective VPATH's.  */
  3168.         pattern = 0;
  3169.       (void) construct_vpath_list (pattern, p);
  3170.       if (pattern != 0)
  3171.         free (pattern);
  3172.       if (p != 0)
  3173.         free (p);
  3174.       continue;
  3175.     }
  3176. #undef    word1eq
  3177.       else if (try_macro_definition (p, o_file))
  3178.     continue;
  3179.       else if (*p == '\t')
  3180.     {
  3181.       /* This line is a shell command */
  3182.       int len;
  3183.  
  3184.       if (filenames == 0)
  3185.         fatal ("%s:%ld: commands commence before first target",
  3186.                filename, lineno);
  3187.  
  3188.       /* Add this command line to end of the line being accumulated.  */
  3189.       if (commands_idx == 0)
  3190.         commands_started = lineno;
  3191.       len = strlen (p);
  3192.       if (len + 1 + commands_idx > commands_len)
  3193.         {
  3194.           commands_len = (len + 1 + commands_idx) * 2;
  3195.           commands = (char *) xrealloc (commands, commands_len);
  3196.         }
  3197.       bcopy (p, &commands[commands_idx], len);
  3198.       commands_idx += len;
  3199.       commands[commands_idx++] = '\n';
  3200.     }
  3201.       else
  3202.     {
  3203.       /* This line describes some target files.
  3204.          Record the previous rule.  */
  3205.  
  3206.       struct commands *cmds;
  3207.  
  3208.       if (commands_idx > 0)
  3209.         {
  3210.           register int i = 0;
  3211.           while (i < commands_idx
  3212.              && (commands[i] == ' ' || commands[i] == '\t'
  3213.              || commands[i] == '\n'))
  3214.         ++i;
  3215.           if (i < commands_idx)
  3216.         {
  3217.           cmds = (struct commands *)
  3218.             xmalloc (sizeof (struct commands));
  3219.           cmds->filename = filename;
  3220.           cmds->lineno = commands_started;
  3221.           cmds->commands = savestring (commands, commands_idx);
  3222.         }
  3223.           else
  3224.         cmds = 0;
  3225.         }
  3226.       else
  3227.         cmds = 0;
  3228.       record_files (filenames, pattern, deps, cmds, two_colon,
  3229.             filename, lineno, !nodefault);
  3230.  
  3231.  
  3232.       /* Does this line contain a semicolon (that isn't quoted with \)?
  3233.          If so, find the first such.  */
  3234.       cmdleft = index (p, ';');
  3235.       while (cmdleft != 0 && cmdleft[-1] == '\\')
  3236.         {
  3237.           register char *q = &cmdleft[-1];
  3238.           register int backslash = 0;
  3239.           while (*q-- == '\\')
  3240.         backslash = !backslash;
  3241.           if (backslash)
  3242.         cmdleft = index (cmdleft + 1, ';');
  3243.           else
  3244.         break;
  3245.         }
  3246.       if (cmdleft != 0)
  3247.         {
  3248.           p = savestring (p, cmdleft - p);
  3249.           p2 = macro_expand (p);
  3250.           free (p);
  3251.         }
  3252.       else
  3253.         p2 = macro_expand (p);
  3254.  
  3255.       if (*p2 == '\0' || *p2 == ':')
  3256.         fatal ("%s:%ld: missing target name", filename, lineno);
  3257.       filenames = multi_glob (parse_file_seq (&p2, ':',
  3258.                           sizeof (struct nameseq)),
  3259.                   sizeof (struct nameseq));
  3260.       if (*p2++ == '\0')
  3261.         fatal ("%s:%ld: missing separator", filename, lineno);
  3262.       /* Is this a one-colon or two-colon entry?  */
  3263.       two_colon = *p2 == ':';
  3264.       if (two_colon) p2++;
  3265.  
  3266.       /* Is this an extended static rule: `target: %targ: %dep; ...'?  */
  3267.       p = index (p2, ':');
  3268.       while (p != 0 && p[-1] == '\\')
  3269.         {
  3270.           register char *q = &p[-1];
  3271.           register int backslash = 0;
  3272.           while (*q-- == '\\')
  3273.         backslash = !backslash;
  3274.           if (backslash)
  3275.         p = index (p + 1, ';');
  3276.           else
  3277.         break;
  3278.         }
  3279.       if (p != 0)
  3280.         {
  3281.           struct nameseq *target;
  3282.           target = parse_file_seq (&p2, ':', sizeof (struct nameseq));
  3283.           ++p2;
  3284.           if (target == 0)
  3285.         fatal ("%s:%ld: missing target pattern", filename, lineno);
  3286.           else if (target->next != 0)
  3287.         fatal ("%s:%ld: multiple target patterns", filename, lineno);
  3288.           pattern = target->name;
  3289.           if (index (pattern, '%') == 0)
  3290.         fatal ("%s:%ld: target pattern contains no `%%'",
  3291.                filename, lineno);
  3292.         }
  3293.       else
  3294.         pattern = 0;
  3295.       
  3296.       /* Parse the dependencies.  */
  3297.       deps = (struct dep *)
  3298.         multi_glob (parse_file_seq (&p2, ';', sizeof (struct dep)),
  3299.             sizeof (struct dep));
  3300.  
  3301.       commands_idx = 0;
  3302.       /* Did we stop at end of line, or at a semicolon?  */
  3303.       if (cmdleft != 0)
  3304.         {
  3305.           /* Semicolon means rest of line is a command */
  3306.           int len = strlen (cmdleft + 1);
  3307.  
  3308.           /* Add this command line to the buffer.  */
  3309.           if (len + 2 > commands_len)
  3310.         {
  3311.           commands_len = (len + 2) * 2;
  3312.           commands = (char *) xrealloc (commands, commands_len);
  3313.         }
  3314.           bcopy (cmdleft + 1, commands, len);
  3315.           commands_idx += len;
  3316.           commands[commands_idx++] = '\n';
  3317.         }
  3318.     }
  3319.     }
  3320.  
  3321.   if (ignoring)
  3322.     fatal ("missing endif");
  3323.  
  3324.   /* At eof, record the last rule.  */
  3325.   {
  3326.     struct commands *cmds;
  3327.  
  3328.     if (commands_idx > 0)
  3329.       {
  3330.     register int i = 0;
  3331.     while (i < commands_idx
  3332.            && (commands[i] == ' ' || commands[i] == '\t'
  3333.                || commands[i] == '\n'))
  3334.       ++i;
  3335.     if (i < commands_idx)
  3336.       {
  3337.         cmds = (struct commands *) xmalloc (sizeof (struct commands));
  3338.         cmds->filename = filename;
  3339.         cmds->lineno = commands_started;
  3340.         cmds->commands = savestring (commands, commands_idx);
  3341.       }
  3342.     else
  3343.       cmds = 0;
  3344.       }
  3345.     else
  3346.       cmds = 0;
  3347.     record_files (filenames, pattern, deps, cmds, two_colon,
  3348.           filename, lineno, !nodefault);
  3349.   }
  3350.  
  3351.   freebuffer (&lb);
  3352.   free ((char *) commands);
  3353.   if (infile != stdin)
  3354.     fclose (infile);
  3355.  
  3356.   reading_filename = 0;
  3357.   reading_lineno_ptr = 0;
  3358. }
  3359.  
  3360. /* Execute a `define' directive.
  3361.    The first line has already been read, and NAME is the name of
  3362.    the variable to be defined.  The following lines remain to be read.
  3363.    LINENO, INFILE and FILENAME refer to the makefile being read.
  3364.    The value returned is LINENO, updated for lines read here.  */
  3365.  
  3366. static long
  3367. do_define (lbp, name, lineno, infile, filename)
  3368.      struct linebuffer *lbp;
  3369.      char *name;
  3370.      long lineno;
  3371.      FILE *infile;
  3372.      char *filename;
  3373. {
  3374.   int length = 0;
  3375.   long nlines = 0L;
  3376.   char *definition = (char *) xmalloc (1);
  3377.   register char *p;
  3378.  
  3379. #define    word1eq(s,l)    ((p[l] == '\0' || p[l] == ' ' || p[l] == '\t') && \
  3380.                          !strncmp (s, p, l))
  3381.  
  3382.   while (!feof (infile))
  3383.     {
  3384.       lineno += nlines;
  3385.       nlines = readline (lbp, infile, filename, lineno);
  3386.  
  3387.       p = lbp->buffer;
  3388.       if (word1eq ("endef", 5))
  3389.     {
  3390.       /* Define the macro.  */
  3391.       define_macro (name, strlen (name), definition, o_file, 1);
  3392.       break;
  3393.     }
  3394.       else
  3395.     {
  3396.       int len = strlen (p);
  3397.       int olength = length;
  3398.  
  3399.       /* Increase the buffer if necessary.  */
  3400.       length += len + (olength != 0);
  3401.       if (olength == 0)
  3402.         definition = (char *) xmalloc (length + 1);
  3403.       else
  3404.         definition = (char *) xrealloc (definition, length + 1);
  3405.  
  3406.       /* Separate lines with a newline.  */
  3407.       if (olength > 0)
  3408.         definition[olength++] = '\n';
  3409.       bcopy (p, &definition[olength], len);
  3410.       definition[length] = 0;
  3411.     }
  3412.     }
  3413.  
  3414.   return lineno;
  3415. }
  3416.  
  3417. /* Glob-expand LINE.
  3418.    The returned pointer is only good until the next call to this
  3419.    routine.
  3420.  
  3421.    The RECURSIVE flag is only used internally.  */
  3422.  
  3423. static char *
  3424. string_glob (line, recursive)
  3425.      char *line;
  3426.      int recursive;
  3427. {
  3428.   static char *result, *result_end;
  3429.   static int result_length = 0;
  3430.   char **globbed;
  3431.   register int i, d, len;
  3432.   register char *p, *s;
  3433.  
  3434.   s = line;
  3435.   while (*s && *s != ' ' && *s != '\t')
  3436.     ++s;
  3437.  
  3438.   p = savestring (line, s - line);
  3439.   globbed = glob_filename (p);
  3440.   free (p);
  3441.  
  3442.   while (*s == ' ' || *s == '\t')
  3443.     ++s;
  3444.  
  3445.   /* NOSTRICT */
  3446.   if ((int) globbed == 0)
  3447.     fatal ("virtual memory exhausted");
  3448.   /* NOSTRICT */
  3449.   else if ((int) globbed == -1)
  3450.     pfatal_with_name (".");
  3451.  
  3452.   if (result_length == 0)
  3453.     {
  3454.       result_length = 200;
  3455.       result = xmalloc (200);
  3456.     }
  3457.  
  3458.   p = recursive ? result_end : result;
  3459.   *p = '\0';
  3460.   for (i = 0; globbed[i] != 0; ++i)
  3461.     {
  3462.       len = strlen (globbed[i]) + 1;
  3463.       d = p - result;
  3464.       if (d > 0)
  3465.     ++d;
  3466.       d += len;
  3467.       if (d > result_length)
  3468.     {
  3469.       result_length = d + (globbed[i + 1] ? 20 : 0);
  3470.       result = xrealloc (result, result_length);
  3471.           p = result + (d - len - (d > len ? 1 : 0));
  3472.     }
  3473.       if (d > len)
  3474.     *p++ = ' ';
  3475.       bcopy (globbed[i], p, len);
  3476.       free (globbed[i]);
  3477.       p += len - 1;
  3478.     }
  3479.   result_end = p;
  3480.   free ((char *) globbed);
  3481.  
  3482.   if (*s != '\0')
  3483.     (void) string_glob (s, 1);
  3484.  
  3485.   return (result);
  3486. }
  3487.  
  3488. /* Interpret conditional commands "ifdef", "ifndef", "ifeq",
  3489.    "ifneq", "else" and "endif".
  3490.    LINE is the input line, with the command as its first word.
  3491.  
  3492.    FILENAME and LINENO are the filename and line number in the
  3493.    current makefile.  They are used for error messages.
  3494.  
  3495.    Value is -1 if the line is invalid,
  3496.    0 if following text should be interpreted,
  3497.    1 if following text should be ignored.  */
  3498.  
  3499. static int
  3500. conditional_line (line, filename, lineno)
  3501.      char *line;
  3502.      char *filename;
  3503.      long lineno;
  3504. {
  3505.   static int if_cmds = 0;
  3506.   static char *ignoring = 0;
  3507.   static int max_ignoring = 0;
  3508.   int notdef;
  3509.   char *cmdname;
  3510.   register int i;
  3511.  
  3512.   if (*line == 'i')
  3513.     {
  3514.       /* It's an "if..." command.  */
  3515.       notdef = line[2] == 'n';
  3516.       if (notdef)
  3517.     {
  3518.       cmdname = line[3] == 'd' ? "ifndef" : "ifneq";
  3519.       line += cmdname[3] == 'd' ? 7 : 6;
  3520.     }
  3521.       else
  3522.     {
  3523.       cmdname = line[2] == 'd' ? "ifdef" : "ifeq";
  3524.       line += cmdname[2] == 'd' ? 6 : 5;
  3525.     }
  3526.     }
  3527.   else
  3528.     {
  3529.       /* It's an "else" or "endif" command.  */
  3530.       notdef = line[1] == 'n';
  3531.       cmdname = notdef ? "endif" : "else";
  3532.       line += notdef ? 5 : 4;
  3533.     }
  3534.  
  3535.   while (*line == ' ' || *line == '\t')
  3536.     ++line;
  3537.  
  3538.   if (*cmdname == 'e')
  3539.     {
  3540.       if (*line != '\0')
  3541.     return -1;
  3542.       /* "Else" or "endif".  */
  3543.       if (if_cmds == 0)
  3544.     fatal ("%s:%ld: extraneous `%s'\n", filename, lineno, cmdname);
  3545.       /* NOTDEF indicates an "endif" command.  */
  3546.       if (notdef)
  3547.     --if_cmds;
  3548.       else
  3549.     ignoring[if_cmds - 1] = !ignoring[if_cmds - 1];
  3550.       for (i = 0; i < if_cmds; ++i)
  3551.     if (ignoring[i]) return 1;
  3552.       return 0;
  3553.     }
  3554.  
  3555.   ++if_cmds;
  3556.  
  3557.   if (if_cmds > (max_ignoring - 1))
  3558.     {
  3559.       max_ignoring += 5;
  3560.       if (ignoring)
  3561.     ignoring = xrealloc (ignoring, max_ignoring);
  3562.       else
  3563.     ignoring = xmalloc (max_ignoring);
  3564.     }
  3565.  
  3566.   if (cmdname[notdef ? 3 : 2] == 'd')
  3567.     {
  3568.       /* "Ifdef" or "ifndef".  */
  3569.       struct macro *m;
  3570.       register char *p = line;
  3571.  
  3572.       while (*p != '\0' && *p != ' ' && *p != '\t')
  3573.     ++p;
  3574.       i = p - line;
  3575.       while (*p == ' ' || *p == '\t')
  3576.     ++p;
  3577.       if (*p != '\0')
  3578.     return -1;
  3579.       m = lookup_macro (line, i);
  3580.       ignoring[if_cmds - 1] = (m && *m->value) == notdef;
  3581.       for (i = 0; i < if_cmds; ++i)
  3582.     if (ignoring[i]) return 1;
  3583.       return 0;
  3584.     }
  3585.   else
  3586.     {
  3587.       /* "Ifeq" or "ifneq".  */
  3588.       char *s1, *s2;
  3589.       int len;
  3590.       char termin = *line == '(' ? ',' : *line;
  3591.  
  3592.       if (termin != ',' && termin != '"' && termin != '\'')
  3593.     return -1;
  3594.  
  3595.       s1 = ++line;
  3596.       /* Find the end of the first string.  */
  3597.       if (termin == ',')
  3598.     {
  3599.       register int count = 0;
  3600.       for (; *line != '\0'; ++line)
  3601.           {
  3602.         if (*line == '(')
  3603.           ++count;
  3604.         else if (*line == ')')
  3605.           --count;
  3606.         else if (*line == ',' && count <= 0)
  3607.           break;
  3608.           }
  3609.     }
  3610.       else
  3611.     while (*line != '\0' && *line != termin)
  3612.       ++line;
  3613.  
  3614.       if (*line == '\0')
  3615.     return -1;
  3616.  
  3617.       *line++ = '\0';
  3618.  
  3619.       s2 = macro_expand (s1);
  3620.       /* We must allocate a new copy of the expanded string because
  3621.      macro_expand re-uses the same buffer.  */
  3622.       len = strlen (s2);
  3623.       s1 = (char *) alloca (len + 1);
  3624.       bcopy (s2, s1, len + 1);
  3625.  
  3626.       /* Find the start of the second string.  */
  3627.       while (*line == ' ' || *line == '\t')
  3628.     ++line;
  3629.  
  3630.       termin = termin == ',' ? ')' : *line;
  3631.       if (termin != ')' && termin != '"' && termin != '\'')
  3632.     return -1;
  3633.       ++line;
  3634.       s2 = line;
  3635.  
  3636.       /* Find the end of the second string.  */
  3637.       if (termin == ')')
  3638.     {
  3639.       register int count = 0;
  3640.       for (; *line != '\0'; ++line)
  3641.           if (*line == '(')
  3642.         ++count;
  3643.           else if (*line == ')')
  3644.         if (count <= 0)
  3645.           break;
  3646.         else
  3647.           --count;
  3648.     }
  3649.       else
  3650.     while (*line != '\0' && *line != termin)
  3651.       ++line;
  3652.       if (*line == '\0')
  3653.     return -1;
  3654.  
  3655.       if (*line != '\0')
  3656.     {
  3657.       *line = '\0';
  3658.       ++line;
  3659.       while (*line == ' ' || *line == '\t')
  3660.         ++line;
  3661.       if (*line != '\0')
  3662.         return -1;
  3663.     }
  3664.       s2 = macro_expand (s2);
  3665.       ignoring[if_cmds - 1] = streq (s1, s2) == notdef;
  3666.       for (i = 0; i < if_cmds; ++i)
  3667.     if (ignoring[i]) return 1;
  3668.       return 0;
  3669.     }
  3670. }
  3671.  
  3672. /* Record a description line for files FILENAMES,
  3673.    with dependencies DEPS, commands to execute COMMANDS.
  3674.    TWO_COLON is nonzero if a double colon was used.
  3675.    If not nil, PATTERN is the `%' pattern to make this
  3676.    an extended static rule.
  3677.  
  3678.    The links of FILENAMES are freed, and so are any names in it
  3679.    that are not incorporated into other data structures.
  3680.  
  3681.    If any of the command lines for a file contain "$(MAKE)"
  3682.    or "${MAKE}" then the file's recursive flag is set.  */
  3683.  
  3684. static void
  3685. record_files (filenames, pattern, deps, commands, two_colon,
  3686.           filename, lineno, set_default)
  3687.      struct nameseq *filenames;
  3688.      char *pattern;
  3689.      struct dep *deps;
  3690.      struct commands *commands;
  3691.      int two_colon;
  3692.      char *filename;
  3693.      long lineno;
  3694.      int set_default;
  3695. {
  3696.   struct nameseq *nextf;
  3697.  
  3698.   for (; filenames != 0; filenames = nextf)
  3699.     {
  3700.       register char *name = filenames->name;
  3701.       char *p = index (name, '%');
  3702.       register struct file *f, *f1;
  3703.       register struct rule *r;
  3704.       register struct dep *d;
  3705.       struct dep *this;
  3706.  
  3707.       nextf = filenames->next;
  3708.       free ((char *) filenames);
  3709.  
  3710.       if (p != 0 && pattern != 0)
  3711.     fatal ("%s:%ld: mixed pattern and static rules", filename, lineno);
  3712.  
  3713.       /* If there are multiple filenames, copy the chain DEPS
  3714.      for all but the last one.  It is not safe for the same deps
  3715.      to go in more than one place in the data base.  */
  3716.       this = nextf != 0 ? copy_dep_chain (deps) : deps;
  3717.  
  3718.       if (pattern != 0)
  3719.     /* If this is an extended static rule:
  3720.        `targets: target%pattern: dep%pattern; cmds',
  3721.        Translate each dependency pattern into a plain filename
  3722.        using the target pattern and this target's filename.  */
  3723.     if (!pattern_matches (pattern, name))
  3724.       {
  3725.         /* Give a warning if the rule is meaningless.  */
  3726.         error ("%s:%ld: target `%s' doesn't match the target pattern",
  3727.            filename, lineno, name);
  3728.         this = 0;
  3729.       }
  3730.     else
  3731.       {
  3732.         /* We use patsubst_expand to do the work of translating
  3733.            the target pattern, the target's name and the dependencies'
  3734.            patterns into plain dependency filenames.  */
  3735.  
  3736.         /* Allocate MACRO_BUFFER if it doesn't exist.  */
  3737.         if (macro_buffer == 0) (void) macro_expand ("");
  3738.  
  3739.         for (d = this; d != 0; d = d->next)
  3740.           {
  3741.         char *o;
  3742.         if (index (d->name, '%') == 0)
  3743.           continue;
  3744.         o = patsubst_expand (macro_buffer, name, pattern, d->name);
  3745.         free (d->name);
  3746.         d->name = savestring (macro_buffer, o - macro_buffer);
  3747.           }
  3748.       }
  3749.       
  3750.       /* Check for a pattern rule.  */
  3751.       if (p != 0)
  3752.     {
  3753.       r = (struct rule *) xmalloc (sizeof (struct rule));
  3754.       r->name = name;
  3755.       r->namelen = strlen (name);
  3756.       r->patsuffix = p + 1;
  3757.       r->terminal = two_colon;
  3758.       r->deps = this;
  3759.       r->cmds = commands;
  3760.       /* If the new rule duplicates an old one, delete the old one. */
  3761.       new_pattern_rule (r, 1);
  3762.       f = 0;
  3763.     }
  3764.       else if (!two_colon)
  3765.     {
  3766.       /* Single-colon.  Combine these dependencies
  3767.          with any others in file's existing record, if any.  */
  3768.       f = enter_file (name);
  3769.       if (f->double_colon)
  3770.         fatal ("target file `%s' has both : and :: entries", f->name);
  3771.       /* Check for two single-colon entries both with commands.
  3772.          Check is_target so that we don't lose on files such as .c.o
  3773.          whose commands were preinitialized.  */
  3774.       if (commands != 0 && f->cmds != 0 && f->is_target)
  3775.         fatal ("target file `%s' has commands specified twice", f->name);
  3776.       f->is_target = 1;
  3777.       if (commands != 0)
  3778.         f->cmds = commands;
  3779.       /* Defining .SUFFIXES with no dependencies
  3780.          clears out the list of suffixes.  */
  3781.       if (f == suffix_file && this == 0)
  3782.         f->deps = 0;
  3783.       else if (f->deps)
  3784.         {
  3785.           d = f->deps;
  3786.           while (d->next != 0)
  3787.         d = d->next;
  3788.           d->next = this;
  3789.         }
  3790.       else
  3791.         f->deps = this;
  3792.     }
  3793.       else
  3794.     {
  3795.       /* Double-colon.  Make a new record even if file has one.  */
  3796.       f1 = lookup_file (name);
  3797.       if (f1 != 0 && !f1->double_colon)
  3798.         fatal ("target file `%s' has both : and :: entries", f->name);
  3799.       f = enter_file (name);
  3800.       f->deps = this;
  3801.       f->cmds = commands;
  3802.       f->double_colon = 1;
  3803.       f->is_target = 1;
  3804.       f->prev = f1;
  3805.     }
  3806.  
  3807.       /* Check for $(MAKE) or ${MAKE} in the commands.  */
  3808.       if (commands != 0
  3809.           && (sindex (commands->commands, 0, "${MAKE}", 7) != 0
  3810.           || sindex (commands->commands, 0, "$(MAKE)", 7) != 0))
  3811.     {
  3812.       if (f != 0)
  3813.         f->recursive = 1;
  3814.       else
  3815.         r->recursive = 1;
  3816.     }
  3817.  
  3818.       /* Free name if not needed further.  */
  3819.       if (f != 0 && name != f->name)
  3820.     free (name);
  3821.  
  3822.       /* See if this is first file seen in a top-level makefile
  3823.      whose name does not start with a `.'.  */
  3824.       if (default_goal_file == 0 && set_default && f && *name != '.')
  3825.     {
  3826.       int reject = 0;
  3827.  
  3828.       /* If this file is a suffix, don't
  3829.          let it be the default goal file.  */
  3830.  
  3831.       for (d = suffix_file->deps; d != 0; d = d->next)
  3832.         if (streq (name, dep_name (d)))
  3833.           {
  3834.         reject = 1;
  3835.         break;
  3836.           }
  3837.  
  3838.       if (!reject)
  3839.         default_goal_file = f;
  3840.     }
  3841.     }
  3842. }
  3843.  
  3844. /* Copy a chain of `struct dep', making a new chain
  3845.    with the same contents as the old one.  */
  3846.  
  3847. static struct dep *
  3848. copy_dep_chain (d)
  3849.      struct dep *d;
  3850. {
  3851.   register struct dep *c;
  3852.   struct dep *firstnew = 0;
  3853.   struct dep *lastnew;
  3854.  
  3855.   while (d)
  3856.     {
  3857.       c = (struct dep *) xmalloc (sizeof (struct dep));
  3858.       bcopy ((char *) d, (char *) c, sizeof (struct dep));
  3859.       c->next = 0;
  3860.       if (firstnew == 0)
  3861.     firstnew = lastnew = c;
  3862.       else
  3863.     lastnew = lastnew->next = c;
  3864.  
  3865.       d = d->next;
  3866.     }
  3867.  
  3868.   return firstnew;
  3869. }
  3870.  
  3871. /* Parse a string into a sequence of filenames
  3872.    represented as a chain of struct nameseq's in reverse order.
  3873.    Return that chain.
  3874.  
  3875.    The string is passed as STRINGP, the address of a string pointer.
  3876.    The string pointer is updated to point at the first character
  3877.    not parsed, which either is a null char or equals STOPCHAR.
  3878.  
  3879.    SIZE is how big to construct chain elements.
  3880.    This is useful if we want them actually to be other structures
  3881.    that have room for additional info.  */
  3882.  
  3883. static struct nameseq *
  3884. parse_file_seq (stringp, stopchar, size)
  3885.      char **stringp;
  3886.      char stopchar;
  3887.      int size;
  3888. {
  3889.   register struct nameseq *new = 0;
  3890.   register struct nameseq *new1;
  3891.   register char *p = *stringp;
  3892.   char *q;
  3893.   char *name;
  3894.   register int c;
  3895.  
  3896.   while (1)
  3897.     {
  3898.       /* Skip whitespace; see if any more names are left.  */
  3899.       while (*p == ' ' || *p == '\t')
  3900.     ++p;
  3901.       if (*p == '\0')
  3902.     break;
  3903.       if (*p == stopchar)
  3904.     break;
  3905.       /* Yes, find end of next name.  */
  3906.       q = p;
  3907.       while (1)
  3908.     {
  3909.       c = *p++;
  3910.       if (c == '\0')
  3911.         break;
  3912.       else if (c == '\\' &&
  3913.                (*p == '\\' || *p == ' ' || *p == '\t' || *p == stopchar))
  3914.         ++p;
  3915.       else if (c == ' ' || c == '\t' || c == stopchar)
  3916.         break;
  3917.     }
  3918.       p--;
  3919.  
  3920.       /* Extract the filename just found, and skip it.  */
  3921.       name = savestring (q, p - q);
  3922.  
  3923.       /* Add it to the front of the chain.  */
  3924.       new1 = (struct nameseq *) xmalloc (size);
  3925.       new1->name = name;
  3926.       new1->next = new;
  3927.       new = new1;
  3928.     }
  3929.  
  3930.   *stringp = p;
  3931.   return (new);
  3932. }
  3933.  
  3934. /* Compare strings *S1 and *S2.
  3935.    Return negative if the first is less, positive if it is greater,
  3936.    zero if they are equal.  */
  3937.  
  3938. static int
  3939. alpha_compare (s1, s2)
  3940.      char **s1, **s2;
  3941. {
  3942.   if (**s1 != **s2)
  3943.     return **s1 - **s2;
  3944.   return strcmp (*s1, *s2);
  3945. }
  3946.  
  3947. /* Remove quoting backslashes from a string
  3948.    by compacting the string down into itself.
  3949.    Backslashes quoted by other backslashes are not removed.  */
  3950.  
  3951. static void
  3952. dequote (string)
  3953.      char *string;
  3954. {
  3955.   register char *in, *out;
  3956.   register int c;
  3957.  
  3958.   in = string;
  3959.   out = string;
  3960.  
  3961.   while (c = *in++)
  3962.     {
  3963.       if (c != '\\')
  3964.     *out++ = c;
  3965.       else if (c = *in++)
  3966.     *out++ = c;
  3967.     }
  3968.  
  3969.   *out = '\0';
  3970. }
  3971.  
  3972. /* Given a chain of struct nameseq's describing a sequence of filenames,
  3973.    in reverse of the intended order,
  3974.    return a new chain describing the result of globbing the filenames.
  3975.    The new chain is in forward order.
  3976.    The links of the old chain are freed or used in the new chain.
  3977.    Likewise for the names in the old chain.
  3978.  
  3979.    SIZE is how big to construct chain elements.
  3980.    This is useful if we want them actually to be other structures
  3981.    that have room for additional info.  */
  3982.  
  3983. static struct nameseq *
  3984. multi_glob (chain, size)
  3985.      struct nameseq *chain;
  3986.      int size;
  3987. {
  3988.   register struct nameseq *new = 0;
  3989.   register struct nameseq *tem;
  3990.   register struct nameseq *old;
  3991.   register char **vector;
  3992.   register int i;
  3993.   int length;
  3994.   struct nameseq *nexto;
  3995.  
  3996.  
  3997.   for (old = chain; old != 0; old = nexto)
  3998.     {
  3999.       nexto = old->next;
  4000.  
  4001.       if (glob_pattern_p (old->name))
  4002.     {
  4003.       vector = glob_filename (old->name);
  4004.       /* NOSTRICT */
  4005.       if ((int) vector == 0)
  4006.         fatal ("virtual memory exhausted");
  4007.       /* NOSTRICT */
  4008.       else if ((int) vector == -1)
  4009.         pfatal_with_name (old->name);
  4010.       free (old->name);
  4011.       for (i = 0; vector[i]; i++);
  4012.       length = i;
  4013.       qsort ((char *) vector, length, sizeof (char *), alpha_compare);
  4014.       for (i = length - 1; i >= 0; i--)
  4015.         {
  4016.           tem = (struct nameseq *) xmalloc (size);
  4017.           tem->name = vector[i];
  4018.           tem->next = new;
  4019.           tem->quotedparen = 1;
  4020.           new = tem;
  4021.         }
  4022.       free ((char *) vector);
  4023.       free ((char *) old);
  4024.     }
  4025.       else
  4026.     {
  4027.       old->quotedparen = !strcmp (old->name + strlen (old->name) - 2,
  4028.                       "\\)");
  4029.       dequote (old->name);
  4030.       old->next = new;
  4031.       new = old;
  4032.     }
  4033.     }
  4034.  
  4035.   return (new);
  4036. }
  4037.  
  4038.  
  4039. /* For each dependency of each file, make it point at the
  4040.    file that it depends on.
  4041.  
  4042.    Also mark the files depended on by .PRECIOUS and .PHONY.  */
  4043.  
  4044. static void
  4045. snap_deps ()
  4046. {
  4047.   register struct file *f;
  4048.   register struct dep *d;
  4049.   register int i;
  4050.  
  4051.   /* Enter each dependency name as a file.  */
  4052.   for (i = 0; i < FILE_BUCKETS; ++i)
  4053.     for (f = files[i]; f != 0; f = f->next)
  4054.       for (d = f->deps; d != 0; d = d->next)
  4055.     {
  4056.       d->file = enter_file (dep_name (d));
  4057.       d->name = 0;
  4058.     }
  4059.   
  4060.  
  4061.   /* Compute maximum length of all the suffixes.  */
  4062.   maxsuffix = 0;
  4063.   for (d = suffix_file->deps; d != 0; d = d->next)
  4064.     {
  4065.       maxsuffix = max (maxsuffix, strlen (dep_name (d)));
  4066.     }
  4067.  
  4068.   f = lookup_file (".PRECIOUS");
  4069.   if (f != 0)
  4070.     for (d = f->deps; d != 0; d = d->next)
  4071.       for (f = d->file; f != 0; f = f->prev)
  4072.     f->precious = 1;
  4073.  
  4074.   f = lookup_file (".PHONY");
  4075.   if (f != 0)
  4076.     for (d = f->deps; d != 0; d = d->next)
  4077.       for (f = d->file; f != 0; f = f->prev)
  4078.     {
  4079.       /* Mark this file as phony and non-existent.  */
  4080.       f->phony = 1;
  4081.       f->last_mtime = -1L;
  4082.     }
  4083. }
  4084.  
  4085. /* If FILE is not up to date, execute the commands for it.
  4086.    Return 0 if successful, 1 if unsuccessful;
  4087.    but with some flag settings, just call `exit' if unsuccessful.
  4088.  
  4089.    DEPTH is the depth in recursions of this function.
  4090.    We increment it during the consideration of our dependencies,
  4091.    then decrement it again after finding out whether this file
  4092.    is out of date.
  4093.  
  4094.    If there are multiple entries for FILE, consider each in turn.  */
  4095.  
  4096. static int
  4097. update_file (file, depth)
  4098.      struct file *file;
  4099.      int depth;
  4100. {
  4101.   register int status;
  4102.   register struct file *f = file;
  4103.   int ofiles_remade = files_remade;
  4104.  
  4105.   while (f)
  4106.     {
  4107.       status = update_file_1 (f, depth);
  4108.       if (status && !keep_going_flag)
  4109.     return (status);
  4110.       f = f->prev;
  4111.     }
  4112.  
  4113.   /* For a top level target, if we have found nothing whatever to do for it,
  4114.      print a message saying nothing needs doing.  */
  4115.  
  4116.   if (ofiles_remade == files_remade
  4117.       && !print_data_base_flag
  4118.       && depth == 0 && !silent_flag && !question_flag)
  4119.     {
  4120.       printf ("%s: File `%s' is up to date.\n", program, file->name);
  4121.       fflush (stdout);
  4122.     }
  4123.  
  4124.   return (status);
  4125. }
  4126.  
  4127. /* Consider a single `struct file' and update it as appropriate.  */
  4128.  
  4129. #define DEBUGPR(msg) \
  4130.   if (debug_flag) \
  4131.     {  print_spaces (depth);  printf (msg, file->name); fflush (stdout);  }
  4132.  
  4133. static int
  4134. update_file_1 (file, depth)
  4135.      struct file *file;
  4136.      int depth;
  4137. {
  4138.   register long this_mtime;
  4139.   int must_make;
  4140.   int dep_status = 0;
  4141.   register struct dep *d;
  4142.  
  4143.   DEBUGPR ("Considering target file `%s'.\n");
  4144.   depth++;
  4145.  
  4146.   if (file->updated)
  4147.     {
  4148.       depth--;
  4149.       if (file->update_status > 0)
  4150.     {
  4151.       DEBUGPR ("Recently tried and failed to update file `%s'.\n");
  4152.       return (file->update_status);
  4153.     }
  4154.  
  4155.       DEBUGPR ("File `%s' was considered already.\n");
  4156.       return 0;
  4157.     }
  4158.   else
  4159.     {
  4160.       file->updating = 1;    /* Notice recursive update of same file.  */
  4161.  
  4162.       /* Looking at the file's modtime beforehand allows the possibility
  4163.      that its name may be changed by a VPATH search, and thus it may
  4164.      not need an implicit rule.  If this were not done, the file
  4165.      might get implicit commands that apply to its initial name, only
  4166.      to have that name replaced with another found by VPATH search.  */
  4167.  
  4168.       this_mtime = file_mtime (file);
  4169.       must_make = this_mtime == -1L;
  4170.       if (must_make)
  4171.     DEBUGPR ("File `%s' does not exist.\n");
  4172.  
  4173.       /* If file was specified as a target with no commands,
  4174.      come up with some default commands */
  4175.  
  4176.       if (!file->phony && file->cmds == 0 && !file->tried_implicit)
  4177.     {
  4178.       if (try_implicit_rule (file, depth))
  4179.         {
  4180.           DEBUGPR ("An implicit rule found for `%s'.\n");
  4181.         }
  4182.       else
  4183.         {
  4184.           DEBUGPR ("No implicit rule found for `%s'.\n");
  4185.           if (default_file)
  4186.         file->cmds = default_file->cmds;
  4187.         }
  4188.       file->tried_implicit = 1;
  4189.     }
  4190.  
  4191.       /* Update all non-intermediate files we depend on, if necessary,
  4192.      and see whether any of them is more recent than this file.  */
  4193.  
  4194.       for (d = file->deps; d != 0; d = d->next)
  4195.     {
  4196.       if (d->file->updating)
  4197.         fatal ("dependency loop involving `%s' and `%s'",
  4198.            dep_name (d), file->name);
  4199.  
  4200.       dep_status |= check_dep (d->file, depth, this_mtime, &must_make);
  4201.       if (dep_status && !keep_going_flag)
  4202.         break;
  4203.     }
  4204.  
  4205.       /* Now we know whether this target needs updating.
  4206.      If it does, update all the intermediate files we depend on.  */
  4207.  
  4208.       if (must_make)
  4209.     {
  4210.       for (d = file->deps; d != 0; d = d->next)
  4211.         if (d->file->intermediate)
  4212.           {
  4213.         dep_status |= update_file (d->file, depth);
  4214.         if (dep_status && !keep_going_flag)
  4215.           break;
  4216.           }
  4217.     }
  4218.  
  4219.       file->updating = 0;
  4220.  
  4221.       DEBUGPR ("Finished dependencies of target file `%s'.\n");
  4222.  
  4223.       if (print_data_base_flag)
  4224.     {
  4225.       depth--;
  4226.       DEBUGPR ("Would now consider updating `%s'.\n");
  4227.       return (0);
  4228.     }
  4229.  
  4230.       /* If any dependency failed, give up now.  */
  4231.  
  4232.       if (dep_status)
  4233.     {
  4234.       depth--;
  4235.       if (depth == 0 && keep_going_flag)
  4236.         {
  4237.           printf ("%s: Target `%s' not remade because of errors.\n",
  4238.               program, file->name);
  4239.           fflush (stdout);
  4240.         }
  4241.       DEBUGPR ("Giving up on target file `%s'.\n");
  4242.       return (dep_status);
  4243.     }
  4244.  
  4245.       /* Now record which dependencies are more recent than this file,
  4246.      so we can create $@.  */
  4247.  
  4248.       for (d = file->deps; d != 0; d = d->next)
  4249.     {
  4250.       d->changed = this_mtime == -1L || this_mtime < file_mtime (d->file);
  4251.  
  4252.       if (debug_flag && this_mtime != -1L)
  4253.         {
  4254.           print_spaces (depth);
  4255.           printf ("File `%s' is %s than file `%s'.\n",
  4256.               file->name, d->changed ? "older" : "newer",
  4257.               dep_name (d));
  4258.           fflush (stdout);
  4259.         }
  4260.     }
  4261.     }
  4262.  
  4263.   /* Here depth returns to the value it had when we were called */
  4264.   depth--;
  4265.  
  4266.   if (!must_make)
  4267.     {
  4268.       DEBUGPR ("No need to remake target file `%s'.\n");
  4269.       file->update_status = 0;
  4270.       file->updated = 1;
  4271.       return (0);
  4272.     }
  4273.  
  4274.   DEBUGPR ("Must remake target file `%s'.\n");
  4275.  
  4276.   /* Now, take appropriate actions to remake the file.  */
  4277.   return remake_file (file);
  4278. }
  4279.  
  4280. /* Check whether another file (whose mtime is THIS_MTIME)
  4281.    needs updating on account of a dependency which is file FILE.
  4282.    If it does, store 1 in *MUST_MAKE_PTR.
  4283.    In the process, update any non-intermediate files
  4284.    that FILE depends on (including FILE itself).
  4285.    Return nonzero if any updating failed.  */
  4286.  
  4287. static int
  4288. check_dep (file, depth, this_mtime, must_make_ptr)
  4289.      struct file *file;
  4290.      int depth;
  4291.      long this_mtime;
  4292.      int *must_make_ptr;
  4293. {
  4294.   register struct dep *d;
  4295.   int dep_status = 0;
  4296.  
  4297.   ++depth;
  4298.   file->updating = 1;
  4299.  
  4300.   if (!file->intermediate)
  4301.     /* If this is a non-intermediate file, update it
  4302.        and record whether it is newer than THIS_MTIME.  */
  4303.     {
  4304.       dep_status = update_file (file, depth);
  4305.       if (file_mtime (file) > this_mtime)
  4306.     *must_make_ptr = 1;
  4307.     }
  4308.   else
  4309.     /* FILE is an intermediate file.
  4310.        Update all non-intermediate files we depend on, if necessary,
  4311.        and see whether any of them is more recent than the file
  4312.        on whose behalf we are checking.  */
  4313.     for (d = file->deps; d != 0; d = d->next)
  4314.       {
  4315.     if (d->file->updating)
  4316.       fatal ("dependency loop involving `%s' and `%s'",
  4317.          dep_name (d), file->name);
  4318.  
  4319.     dep_status |= check_dep (d->file, depth, this_mtime, must_make_ptr);
  4320.     if (dep_status && !keep_going_flag)
  4321.       break;
  4322.       }
  4323.  
  4324.   file->updating = 0;
  4325.   return dep_status;
  4326. }
  4327.  
  4328. /* Having checked and updated the dependencies of FILE,
  4329.    do whatever is appropriate to remake FILE itself.
  4330.    Return the status from executing FILE's commands.  */
  4331.  
  4332. static int
  4333. remake_file (file)
  4334.      struct file *file;
  4335. {
  4336.   int status;
  4337.  
  4338.   file->update_status = 0;
  4339.   files_remade++;
  4340.  
  4341.   /* If file is a recursive submake, ignore -t and -q for this file.  */
  4342.  
  4343.   if (!file->is_target && !file->phony && file->cmds == 0)
  4344.     {
  4345.       fprintf (stderr, "%s: *** No specificaton for making file `%s'.",
  4346.            program, file->name);
  4347.       if (keep_going_flag)
  4348.     {
  4349.       fputs ("  Continuing.\n", stderr);
  4350.       status = 1;
  4351.     }
  4352.       else
  4353.     {
  4354.       fputs ("  Stop.\n", stderr);
  4355.       exit (1);
  4356.     }
  4357.     }
  4358.   else if (question_flag && !file->recursive)
  4359.     /* pretend that updating "failed".  */
  4360.     status = 1;
  4361.   else if (file->cmds == 0)
  4362.     /* The only effect of this if statement
  4363.        is that files with no commands (not even implicit ones)
  4364.        and files marked as phony do not get touched with -t.  */
  4365.     status = 0;
  4366.   else if (touch_flag && !file->phony && !file->recursive)
  4367.     {
  4368.       /* Should set file's modification date and do nothing else.  */
  4369.       if (!silent_flag)
  4370.     {
  4371.       printf ("touch %s\n", file->name);
  4372.       fflush (stdout);
  4373.     }
  4374.  
  4375.       if (ar_name (file->name))
  4376.     status = ar_touch (file->name);
  4377.       else
  4378.     {
  4379.       int fd = open (file->name, O_RDWR | O_CREAT, 0666);
  4380.  
  4381. #define    TOUCH_ERROR(call) \
  4382.   if (1) { perror_with_name (call, file->name); goto end_touch; } else
  4383.  
  4384.       status = fd < 0;
  4385.       if (status)
  4386.         TOUCH_ERROR ("touch: open: ");
  4387.       else
  4388.         {
  4389.           struct stat statbuf;
  4390.           char buf;
  4391.  
  4392.           if (fstat (fd, &statbuf) < 0)
  4393.         TOUCH_ERROR ("touch: fstat: ");
  4394.           /* Rewrite character 0 same as it already is.  */
  4395.           if (read (fd, &buf, 1) < 0)
  4396.         TOUCH_ERROR ("touch: read: ");
  4397.           if (lseek (fd, 0, 0) < 0L)
  4398.         TOUCH_ERROR ("touch: lseek: ");
  4399.           if (write (fd, &buf, 1) < 0)
  4400.         TOUCH_ERROR ("touch: write: ");
  4401.           /* If file length was 0, we just changed it.
  4402.          So change it back.  */
  4403.           if (statbuf.st_size == 0)
  4404.         if (ftruncate (fd, 0) < 0)
  4405.           TOUCH_ERROR ("touch: ftruncate: ");
  4406.           close (fd);
  4407.         }
  4408.       end_touch:;
  4409.  
  4410.     }
  4411.     }
  4412.   else
  4413.     status = execute_file_commands (file);
  4414.  
  4415.   file->update_status = status;
  4416.   file->last_mtime = just_print_flag
  4417.                      ? time ((long *) 0) : name_mtime (file->name);
  4418.   file->updated = 1;
  4419.  
  4420.   return (status);
  4421. }
  4422.  
  4423. /* Discard each backslash-newline combination from LINE.
  4424.    This is done by copying the text at LINE into itself.  */
  4425.  
  4426. static void
  4427. collapse_continuations (line)
  4428.      char *line;
  4429. {
  4430.   register char *in, *out;
  4431.  
  4432.   in = out = line;
  4433.  
  4434.   while (*in)
  4435.     {
  4436.       if (in[0] == '\\')
  4437.     {
  4438.       if (in[1] == '\n')
  4439.         {
  4440.           in += 2;
  4441.           *out++ = ' ';
  4442.         }
  4443.       else
  4444.         {
  4445.           *out++ = *in++;
  4446.           if (in[0] != '\0')
  4447.         *out++ = *in++;
  4448.         }
  4449.     }
  4450.       else
  4451.     *out++ = *in++;
  4452.     }
  4453.  
  4454.   *out = '\0';
  4455.  
  4456.   return;
  4457. }
  4458.  
  4459. /* Execute the commands associated with FILE.
  4460.    Returns nonzero if some command got an unignored error.
  4461.    Returns zero if have successfully executed the commands.  */
  4462.  
  4463. static int
  4464. execute_file_commands (file)
  4465.      struct file *file;
  4466. {
  4467.   register char *line, *p, *next;
  4468.   /* Set to zero if we see that it is not safe
  4469.      to execute commands directly.  */
  4470.   int use_internal = 1;
  4471.   int status = 0;
  4472.   char *expansion;
  4473.   struct commands *cmds = file->cmds;
  4474.  
  4475.   /* Don't go through all the preparations if the
  4476.      command is nothing but whitespace.  */
  4477.  
  4478.   for (p = cmds->commands; *p; ++p)
  4479.     if (*p != ' ' && *p != '\t' && *p != '\n')
  4480.       break;
  4481.   if (*p == '\0')
  4482.     return 0;
  4483.  
  4484.   /* First set the automatic macros according to this file */
  4485.  
  4486.   free (atD_macro->value);
  4487.   free (starD_macro->value);
  4488.   free (lessD_macro->value);
  4489.   free (percentD_macro->value);
  4490.   free (at_macro->value);
  4491.   free (percent_macro->value);
  4492.  
  4493. #ifdef atarist
  4494.  
  4495. #define    LASTSLASH(m)    rindex (m->value, '\\')
  4496. #define    FILEONLY(m)    line ? line + 1 : m->value
  4497. #define    DIRONLY(m)    line == 0 ? savestring (".\\", 2) :        \
  4498.             ((line == m->value) ? savestring ("\\", 1) :    \
  4499.             savestring (m->value, line - m->value + 1))
  4500.  
  4501. #else
  4502.  
  4503. #define    LASTSLASH(m)    rindex (m->value, '/')
  4504. #define    FILEONLY(m)    line ? line + 1 : m->value
  4505. #define    DIRONLY(m)    line == 0 ? savestring ("./", 2) :        \
  4506.             ((line == m->value) ? savestring ("//", 1) :    \
  4507.             savestring (m->value, line - m->value + 1))
  4508.  
  4509. #endif
  4510.  
  4511.   if (ar_name (file->name))
  4512.     {
  4513.       line = index (file->name, '(');
  4514.       at_macro->value = savestring (file->name, line - file->name);
  4515.       ++line;
  4516.       percent_macro->value = savestring (line, strlen (line) - 1);
  4517.     }
  4518.   else
  4519.     {
  4520.       at_macro->value = savestring (file->name, strlen (file->name));
  4521.       percent_macro->value = savestring ((char *) 0, 0);
  4522.     }
  4523.   star_macro->value = file->stem != 0 ? file->stem : "";
  4524.   less_macro->value = file->deps != 0 ? dep_name (file->deps) : "";
  4525.   line = LASTSLASH (at_macro);
  4526.   atF_macro->value = FILEONLY (at_macro);
  4527.   atD_macro->value = DIRONLY (at_macro);
  4528.   dollar_slash_macro->value = atF_macro->value;
  4529.   line = LASTSLASH (star_macro);
  4530.   starF_macro->value = FILEONLY (star_macro);
  4531.   starD_macro->value = DIRONLY (star_macro);
  4532.   line = LASTSLASH (less_macro);
  4533.   lessF_macro->value = FILEONLY (less_macro);
  4534.   lessD_macro->value = DIRONLY (less_macro);
  4535.   line = LASTSLASH (percent_macro);
  4536.   percentF_macro->value = FILEONLY (percent_macro);
  4537.   percentD_macro->value = DIRONLY (percent_macro);
  4538. #undef    LASTSLASH
  4539. #undef    FILEONLY
  4540. #undef    DIRONLY
  4541.  
  4542.   /* Compute the values for $^ and $?.  */
  4543.  
  4544.   {
  4545.     register int dep_size = 0, c_size = 0;
  4546.     register char *cline;
  4547.     register struct dep *d;
  4548.  
  4549.     for (d = file->deps; d != 0; d = d->next)
  4550.       {
  4551.     register int i = strlen (dep_name (d)) + 1;
  4552.     c_size += i;
  4553.     if (d->changed)
  4554.       dep_size += i;
  4555.       }
  4556.  
  4557.     /* Add 1 to size here to make room for the null that
  4558.        `strcat' inserts after the final space.  */
  4559.     line = (char *) xmalloc (dep_size + 1);
  4560.     cline = (char *) xmalloc (c_size + 1);
  4561.     *line = *cline = '\0';
  4562.  
  4563.     if (c_size > 0)
  4564.       {
  4565.     for (d = file->deps; d != 0; d = d->next)
  4566.       {
  4567.         strcat (cline, dep_name (d));
  4568.         strcat (cline, " ");
  4569.         if (d->changed)
  4570.           {
  4571.         strcat (line, dep_name (d));
  4572.         strcat (line, " ");
  4573.           }
  4574.       }
  4575.     /* remove final space */
  4576.     line[dep_size - 1] = cline[c_size - 1] = '\0';
  4577.       }
  4578.     caret_macro->value = cline;
  4579.     qmark_macro->value = line;
  4580.   }
  4581.  
  4582.   /* Arrange for fatal signal to delete this target,
  4583.      unless it depends on .PRECIOUS:  */
  4584.  
  4585.   if (!file->precious)
  4586.     {
  4587.       signal_delete_file = file->name;
  4588.       signal_delete_mtime = file->last_mtime;
  4589.     }
  4590.  
  4591.   /* Expand macros and functions.  Error messages refer to
  4592.      the file and line where these commands were found.  */
  4593.   reading_filename = cmds->filename;
  4594.   reading_lineno_ptr = &(cmds->lineno);
  4595.   next = expansion = macro_expand (cmds->commands);
  4596.   reading_filename = 0;
  4597.   reading_lineno_ptr = 0;
  4598.  
  4599.   /* Now execute the command lines */
  4600.  
  4601.   line = (char *) alloca (strlen (expansion) + 1);
  4602.   while (next && *next)
  4603.     {
  4604.       int noprint = 0;
  4605.       int noerror = 0;
  4606.       char *end = next;
  4607.  
  4608.       /* Find the end of this line.  Backslash-newlines don't
  4609.      mean the end.  */
  4610.  
  4611.       while (*end && *end != '\n')
  4612.     {
  4613.       if (end[0] == '\\' && end[1] != 0)
  4614.         end += 2;
  4615.       else
  4616.         end++;
  4617.     }
  4618.  
  4619.       strncpy (line, next, end - next);
  4620.       line[end - next] = 0;
  4621.       next = *end ? end + 1 : 0;
  4622.  
  4623.       /* Print each line that does not start with `@',
  4624.      unless -s was specified.  */
  4625.       while (*line)
  4626.     {
  4627.       if (*line == '@')
  4628.         noprint = 1;
  4629.       else if (*line == '-')
  4630.         noerror = 1;
  4631.       else if (*line != ' ' && *line != '\t')
  4632.         break;
  4633.       line++;
  4634.     }
  4635.  
  4636.       if (just_print_flag || (!silent_flag && !noprint))
  4637.     {
  4638.       puts (line);
  4639.       fflush (stdout);
  4640.     }
  4641.  
  4642.       /* If -n was specified, don't really execute, unless file
  4643.      is a recursive submake.
  4644.      But do pretend we changed this file's date.  */
  4645.       if (just_print_flag && !file->recursive)
  4646.     continue;
  4647.  
  4648.       /* Delete backslash-newlines from this line.  */
  4649.  
  4650.       collapse_continuations (line);
  4651.  
  4652.       /* Execute the command line.  */
  4653.  
  4654.       status = execute_command_line (line);
  4655.  
  4656.       if (status)
  4657.     {
  4658.       fprintf (stderr, "%s: *** ", program);
  4659.       if (status & SIGNAL_STATUS)
  4660.         {
  4661.           extern char *sys_siglist[];
  4662.           int sig = status & ~(SIGNAL_STATUS|SIGNAL_COREDUMP);
  4663.           if (sig < NSIG)
  4664.         fputs (sys_siglist[sig], stderr);
  4665.           else
  4666.         fprintf (stderr, "Signal %d", sig);
  4667.           if (status & SIGNAL_COREDUMP)
  4668.         fputs (" (core dumped)", stderr);
  4669.         }
  4670.       else
  4671.         fprintf (stderr, "Error %d", status);
  4672.  
  4673.       if (ignore_errors_flag || noerror)
  4674.         {
  4675.           fputs (" (ignored)\n", stderr);
  4676.           /* We say it succeeded anyway so other things
  4677.          that depend on this target will still be made.  */
  4678.           status = 0;
  4679.         }
  4680.       else
  4681.         {
  4682.           putc ('\n', stderr);
  4683.           fflush (stderr);
  4684.           break;
  4685.         }
  4686.     }
  4687.     }
  4688.  
  4689.   /* Target is final; no further reason to delete it.  */
  4690.   signal_delete_file = 0;
  4691.   signal_delete_mtime = 0;
  4692.  
  4693.   /* Now free the macro values made above.  */
  4694.   free (caret_macro->value);
  4695.   free (qmark_macro->value);
  4696.   caret_macro->value = qmark_macro->value = "";
  4697.  
  4698.   return (status);
  4699. }
  4700.  
  4701. /* For a FILE which has no commands specified, try to figure out some
  4702.    from the implicit pattern rules.
  4703.    Returns 1 if a suitable implicit rule was found,
  4704.    after modifying FILE to contain the appropriate commands and deps,
  4705.    or returns 0 if no implicit rule was found.  */
  4706.  
  4707. static int
  4708. try_implicit_rule (file, depth)
  4709.      struct file *file;
  4710.      int depth;
  4711. {
  4712.   register char *filename;
  4713.  
  4714.   DEBUGPR ("Looking for an implicit rule for `%s'.\n");
  4715.  
  4716.   /* If this is an archive member reference,
  4717.      use just the archive member name to search for implicit rules.  */
  4718.   if (ar_name (file->name))
  4719.     {
  4720.       filename = index (file->name, '(');
  4721.       DEBUGPR ("Looking for archive-member implicit rule for `%s'.\n");
  4722.       if (pattern_search (file, filename, depth, 0))
  4723.     return 1;
  4724.     }
  4725.  
  4726.   return pattern_search (file, (char *) 0, depth, 0);
  4727. }
  4728.  
  4729. #define DEBUGP2(msg, a1, a2) \
  4730.   if (debug_flag) \
  4731.     { print_spaces (depth); printf (msg, a1, a2); fflush (stdout);  }
  4732.  
  4733. /* Search the pattern rules for a rule with an existing
  4734.    dependent to make NAME.  If NAME is nil,
  4735.    FILE->name is used.  If a rule is found, the
  4736.    appropriate commands and deps are put in FILE
  4737.    and 1 is returned.  If not, 0 is returned.
  4738.  
  4739.    If an intermediate file is found by pattern search,
  4740.    the intermediate file is set up as a target by the recursive call
  4741.    and is also made a dependency of FILE.
  4742.  
  4743.    DEPTH is used for debugging messages.  */
  4744.  
  4745. static int
  4746. pattern_search (file, name, depth, recursions)
  4747.      struct file *file;
  4748.      char *name;
  4749.      int depth;
  4750.      int recursions;
  4751. {
  4752.   /* Filename we are searching for a rule for.  */
  4753.   char *filename = name != 0 ? name : file->name;
  4754.  
  4755.   /* Length of FILENAME.  */
  4756.   int namelen = strlen (filename);
  4757.  
  4758.   /* The last slash in FILENAME (or nil if there is none).  */
  4759.   char *lastslash;
  4760.  
  4761.   /* This is a file-object used as an argument in
  4762.      recursive calls.  It never contains any data
  4763.      except during a recursive call.  */
  4764.   struct file *intermediate_file = 0;
  4765.  
  4766.   /* Number of dependencies of the current rule that
  4767.      have been found using a recursive pattern_search.  */
  4768.   int intermediate_files_found = 0;
  4769.  
  4770.   /* List of dependencies found recursively.  */
  4771.   struct file **intermediate_files
  4772.     = (struct file **) alloca (max_pattern_deps * sizeof (struct file *));
  4773.  
  4774.   /* List of patterns used to find intermediate targets.  */
  4775.   char **intermediate_patterns
  4776.     = (char **) alloca (max_pattern_deps * sizeof (char *));
  4777.  
  4778.   /* This buffer records all the dependencies actually found for a rule.  */
  4779.   char **found_files = (char **) alloca (max_pattern_deps * sizeof (char *));
  4780.   /* Number of dep names now in FOUND_FILES.  */
  4781.   int deps_found;
  4782.  
  4783.   /* Names of possible dependencies are constructed in this buffer.  */
  4784.   register char *depname = (char *) alloca (namelen + max_pattern_dep_length);
  4785.  
  4786.   /* The start and length of the stem of FILENAME for the current rule.  */
  4787.   register char *stem;
  4788.   register int stemlen;
  4789.  
  4790.   /* Buffer in which we store all the rules that are possibly applicable.  */
  4791.   struct rule **tryrules
  4792.     = (struct rule **) alloca (num_pattern_rules * sizeof (struct rule *));
  4793.  
  4794.   /* Number of valid elements in tryrules.  */
  4795.   int nrules = 0;
  4796.  
  4797.   /* Nonzero if should consider intermediate files as dependencies.  */
  4798.   int intermed_ok;
  4799.  
  4800.   /* Nonzero if we have matched a pattern-rule target
  4801.      that is not just `%'.  */
  4802.   int specific_rule_matched = 0;
  4803.  
  4804.   register int i;
  4805.   register struct rule *rule;
  4806.   register struct dep *dep;
  4807.  
  4808.   char *p;
  4809.  
  4810.   /* Set LASTSLASH to point at the last slash in FILENAME
  4811.      but not counting any slash at the end.  (foo/bar/ counts as
  4812.      bar/ in directory foo/, not empty in directory foo/bar/.)  */
  4813.  
  4814.   lastslash = 0;
  4815.   p = filename;
  4816.   while (*p && p[1])
  4817.     {
  4818. #ifdef atarist
  4819.       if (*p == '\\')
  4820. #else
  4821.       if (*p == '/')
  4822. #endif
  4823.     lastslash = p;
  4824.       p++;
  4825.     }
  4826.  
  4827.   /* First see which pattern rules match this target
  4828.      and may be considered.  Put them in TRYRULES.  */
  4829.  
  4830.   for (rule = pattern_rules; rule != 0; rule = rule->next)
  4831.     {
  4832.       int check_lastslash;
  4833.       /* If the pattern rule has no commands, ignore it.
  4834.      Users cancel built-in rules by redefining them without commands.  */
  4835.       if (rule->deps != 0 && rule->cmds == 0)
  4836.     continue;
  4837.  
  4838.       /* If this rule is in use by a parent pattern_search,
  4839.      don't use it here.  */
  4840.       if (rule->in_use)
  4841.     continue;
  4842.  
  4843.       /* Don't try rules whose dependents are guaranteed
  4844.      to be non-existent.  */
  4845.       if (lastslash == 0 && rule->subdir)
  4846.     continue;
  4847.  
  4848.       /* From the lengths of the filename and the pattern parts,
  4849.      find the stem: the part of the filename that matches the %.  */
  4850.       stem = filename + (rule->patsuffix - rule->name - 1);
  4851.       stemlen = namelen - rule->namelen + 1;
  4852.  
  4853.       /* Set CHECK_LASTSLASH if FILENAME contains a directory prefix
  4854.      and the target pattern does not contain a slash.  */
  4855.  
  4856. #ifdef atarist
  4857.       check_lastslash = lastslash && index (rule->name, '\\') == 0;
  4858. #else
  4859.       check_lastslash = lastslash && index (rule->name, '/') == 0;
  4860. #endif
  4861.       if (check_lastslash)
  4862.     {
  4863.       /* In that case, don't include the directory prefix in STEM here.  */
  4864.       stem += lastslash - filename + 1;
  4865.       stemlen -= (lastslash - filename) + 1;
  4866.     }
  4867.  
  4868.       /* Check that filename is long enough to match the whole pattern.  */
  4869.       if (stemlen <= 0)
  4870.     continue;
  4871.  
  4872.       /* Check that the rule pattern matches the text before the stem.  */
  4873.       if (check_lastslash)
  4874.     {
  4875.       if (stem > (lastslash + 1)
  4876.           && strncmp (rule->name, lastslash + 1, stem - lastslash - 1))
  4877.         continue;
  4878.     }
  4879.       else if (stem > filename
  4880.                && strncmp (rule->name, filename, stem - filename))
  4881.     continue;
  4882.  
  4883.       /* Check that the rule pattern matches the text after the stem.
  4884.      We could test simply !streq (rule->patsuffix, stem + stemlen)
  4885.      but this way we compare the first two characters immediately.
  4886.      This saves time in the very common case where the first
  4887.      character matches because it is a period.  */
  4888.       if (*rule->patsuffix != stem[stemlen]
  4889.       || (*rule->patsuffix != 0
  4890.           && !streq (&rule->patsuffix[1], &stem[stemlen + 1])))
  4891.     continue;
  4892.  
  4893.       /* Record if we match some rule that not all filenames will match.  */
  4894.       if (rule->name[1] != '\0')
  4895.     specific_rule_matched = 1;
  4896.  
  4897.       /* A rule with no dependencies and no commands exists solely to set
  4898.      specific_rule_matched when it matches.  Don't try to use it.  */
  4899.       if (rule->deps != 0 || rule->cmds != 0)
  4900.     tryrules[nrules++] = rule;
  4901.     }
  4902.  
  4903.   /* If we have found a matching rule that won't match all filenames,
  4904.      retroactively reject any "terminal" rules that do always match.  */
  4905.   if (specific_rule_matched)
  4906.     for (i = 0; i < nrules; ++i)
  4907.       if (tryrules[i]->terminal && tryrules[i]->name[1] == '\0')
  4908.     tryrules[i] = 0;
  4909.  
  4910.   /* Try each rule once without intermediate files,
  4911.      then once with them.  */
  4912.   for (intermed_ok = 0; intermed_ok < 2; intermed_ok++)
  4913.     {
  4914.       /* Try each pattern rule till we find one that applies.
  4915.      If it does, copy the names of its dependencies (as substituted)
  4916.      and store them in FOUND_FILES.  DEPS_FOUND is the number of them.  */
  4917.       for (i = 0; i < nrules; i++)
  4918.     {
  4919.       int check_lastslash;
  4920.  
  4921.       rule = tryrules[i];
  4922.  
  4923.       /* RULE is nil when we discovered that a rule, already placed
  4924.          in TRYRULES, should not be applied.  */
  4925.       if (rule == 0)
  4926.         continue;
  4927.  
  4928.       /* Rules that can match any filename and are not terminal
  4929.          should be ignored on the second pass, so that they
  4930.          cannot accept an intermediate file.
  4931.          These rules can only be the end of a chain.  */
  4932.       if (intermed_ok && rule->name[1] == '\0' && !rule->terminal)
  4933.         continue;
  4934.  
  4935.       /* Mark this rule as in use so a recursive
  4936.          pattern_search won't try to use it.  */
  4937.       rule->in_use = 1;
  4938.  
  4939.       /* From the lengths of the filename and the pattern parts,
  4940.          find the stem: the part of the filename that matches the %.  */
  4941.       stem = filename + (rule->patsuffix - rule->name) - 1;
  4942.       stemlen = namelen - rule->namelen + 1;
  4943.  
  4944. #ifdef atarist
  4945.       check_lastslash = lastslash && index (rule->name, '\\') == 0;
  4946. #else
  4947.       check_lastslash = lastslash && index (rule->name, '/') == 0;
  4948. #endif
  4949.       if (check_lastslash)
  4950.         {
  4951.           stem += lastslash - filename + 1;
  4952.           stemlen -= (lastslash - filename) + 1;
  4953.         }
  4954.  
  4955.       DEBUGP2 ("Trying pattern rule with stem `%.*s'.\n",
  4956.            stemlen, stem);
  4957.  
  4958.       /* Try each dependency; see if it "exists".  */
  4959.  
  4960.       intermediate_files_found = 0;
  4961.       deps_found = 0;
  4962.       for (dep = rule->deps; dep != 0; dep = dep->next)
  4963.         {
  4964.           char *p = index (dep_name (dep), '%');
  4965.           char *target_pattern;
  4966.           struct file *f;
  4967.  
  4968.           /* If the dependency name has a %, substitute the stem.  */
  4969.           if (p != 0)
  4970.         {
  4971.           int i;
  4972.           if (check_lastslash)
  4973.             {
  4974.               i = lastslash - filename + 1;
  4975.               bcopy (filename, depname, i);
  4976.             }
  4977.           else
  4978.             i = 0;
  4979.           bcopy (dep_name (dep), depname + i, p - dep_name (dep));
  4980.           i += p - dep_name (dep);
  4981.           bcopy (stem, depname + i, stemlen);
  4982.           i += stemlen;
  4983.            strcpy (depname + i, p + 1);
  4984.           p = depname;
  4985.           target_pattern = dep_name (dep);
  4986.         }
  4987.           else
  4988.         {
  4989.           target_pattern = 0;
  4990.           p = dep_name (dep);
  4991.         }
  4992.           
  4993.           /* P is now the actual dependency name as substituted.  */
  4994.  
  4995.           if (file_impossible_p (p))
  4996.         {
  4997.           /* If this dependency has already been ruled
  4998.              "impossible", then the rule fails
  4999.              and don't bother trying it on the second pass either
  5000.              since we know that will fail too.  */
  5001.           DEBUGP2 ("Rejecting impossible %s dependent `%s'.\n",
  5002.                p == depname ? "implicit" : "rule", p);
  5003.           tryrules[i] = 0;
  5004.           break;
  5005.         }
  5006.  
  5007.           DEBUGP2 ("Trying %s dependent `%s'.\n",
  5008.                p == depname ? "implicit" : "rule", p);
  5009.           if (lookup_file (p) != 0 || file_exists_p (p))
  5010.         {
  5011.           found_files[deps_found++] = savestring (p, strlen (p));
  5012.           continue;
  5013.         }
  5014.           /* This code, given FILENAME = "lib/foo.o",
  5015.          dependency name "lib/foo.c", and VPATH=src,
  5016.          searches for "src/lib/foo.c".  */
  5017.           if (vpath_search (&p, (char *) 0, 0))
  5018.         {
  5019.           DEBUGP2 ("Found dependent as `%s'.\n", p, 0);
  5020.           found_files[deps_found++] = p;
  5021.           continue;
  5022.         }
  5023.  
  5024.           /* We could not find the file in any place we should look.  */
  5025.           /* Try to make this dependency as an intermediate file,
  5026.          but only on the second pass.  */
  5027.  
  5028.           if (intermed_ok && p == depname)
  5029.         {
  5030.           int i;
  5031.  
  5032.           if (intermediate_file == 0)
  5033.             intermediate_file
  5034.               = (struct file *) alloca (sizeof (struct file));
  5035.  
  5036.           DEBUGP2 ("Looking for rule with intermediate file `%s'.\n",
  5037.                p, 0);
  5038.  
  5039.           bzero ((char *) intermediate_file, sizeof (struct file));
  5040.           intermediate_file->name = p;
  5041.           i = pattern_search (intermediate_file, (char *) 0,
  5042.                               depth + 1, recursions + 1);
  5043.           if (i)
  5044.             {
  5045.               p = savestring (p, strlen (p));
  5046.               intermediate_patterns[deps_found]
  5047.             = intermediate_file->name;
  5048.               found_files[deps_found++] = p;
  5049.               intermediate_file->name = p;
  5050.               intermediate_files[intermediate_files_found++]
  5051.             = intermediate_file;
  5052.               intermediate_file = 0;
  5053.               continue;
  5054.             }
  5055.           /* If we have tried to find P as an intermediate file
  5056.              and failed, mark that name as impossible
  5057.              so we won't go through the search again later.  */
  5058.           file_impossible (p);
  5059.         }
  5060.           
  5061.           /* A dependency of this rule does not exist.
  5062.          Therefore, this rule fails.  */
  5063.           break;
  5064.         }
  5065.  
  5066.       /* This rule is no longer "in use" for recursive searches.  */
  5067.       rule->in_use = 0;
  5068.  
  5069.       if (dep != 0)
  5070.         {
  5071.           /* This pattern rule does not apply.
  5072.          If some of its dependents succeeded,
  5073.          free the data structure describing them.  */
  5074.           while (deps_found-- > 0)
  5075.         free (found_files[deps_found]);
  5076.           while (intermediate_files_found-- > 0)
  5077.         {
  5078.           register struct file *f
  5079.             = intermediate_files[intermediate_files_found];
  5080.           if (f->stem < f->name
  5081.               || (f->stem > f->name
  5082.               && (f->stem - f->name) <= strlen (f->name)))
  5083.             free (f->stem);
  5084.         }
  5085.         }
  5086.       else
  5087.         /* This pattern rule does apply.  Stop looking for one.  */
  5088.         break;
  5089.     }
  5090.  
  5091.       /* If we found an applicable rule with intermed_ok == 0,
  5092.      don't try intermed_ok == 1.  */
  5093.       if (i < nrules)
  5094.     break;
  5095.  
  5096.       rule = 0;
  5097.     }
  5098.  
  5099.   /* RULE is nil if the loop went all the way through
  5100.      the list and everything failed.  */
  5101.   if (rule == 0)
  5102.     return 0;
  5103.  
  5104.   /* If we are recursing, store the pattern that matched
  5105.      FILENAME in FILE->name for use in upper levels.  */
  5106.  
  5107.   if (recursions > 0)
  5108.     /* Kludge-o-matic */
  5109.     file->name = rule->name;
  5110.   
  5111.   /* FOUND_FILES lists the dependencies for the rule we found.
  5112.      This includes the intermediate file, if any.
  5113.      Convert them into entries on the deps-chain of FILE.  */
  5114.  
  5115.   while (deps_found-- > 0)
  5116.     {
  5117.       register char *s;
  5118.  
  5119.       dep = (struct dep *) xmalloc (sizeof (struct dep));
  5120.       s = found_files[deps_found];
  5121.       if (recursions == 0)
  5122.     {
  5123.       dep->name = 0;
  5124.       dep->file = enter_file (s);
  5125.     }
  5126.       else
  5127.     {
  5128.       dep->name = s;
  5129.     }
  5130.       dep->next = file->deps;
  5131.       file->deps = dep;
  5132.  
  5133.       /* If the new dependency duplicates an old one, delete the old one. */
  5134.       while (dep)
  5135.     {
  5136.       if (dep->next && streq (dep_name (dep->next), s))
  5137.         dep->next = dep->next->next;
  5138.       else
  5139.         dep = dep->next;
  5140.     }
  5141.     }
  5142.  
  5143.   file->stem = stem[stemlen] == '\0' ? stem : savestring (stem, stemlen);
  5144.   file->cmds = rule->cmds;
  5145.   file->recursive = file->recursive || rule->recursive;
  5146.  
  5147.   /* If we need to use an intermediate file,
  5148.      make sure it is entered as a target, with the info that was
  5149.      found for it in the recursive pattern_search call.
  5150.      We know that the intermediate file did not already exist as
  5151.      a target; therefore we can assume that the deps and cmds
  5152.      of F below are null before we change them.  */
  5153.  
  5154.   while (intermediate_files_found-- > 0)
  5155.     {
  5156.       struct file *imf = intermediate_files[intermediate_files_found];
  5157.       register struct file *f = enter_file (imf->name);
  5158.       f->deps = imf->deps;
  5159.       f->cmds = imf->cmds;
  5160.       f->stem = imf->stem;
  5161.       imf = lookup_file (intermediate_patterns[intermediate_files_found]);
  5162.       if (imf != 0 && imf->precious)
  5163.     f->precious = 1;
  5164.       f->intermediate = 1;
  5165.       f->tried_implicit = 1;
  5166.       for (dep = f->deps; dep != 0; dep = dep->next)
  5167.     {
  5168.       dep->file = enter_file (dep->name);
  5169.       dep->name = 0;
  5170.     }
  5171.       num_intermediates++;
  5172.     }
  5173.  
  5174.   return 1;
  5175. }
  5176.  
  5177. /* Compute the maximum dependency length and maximum number of
  5178.    dependencies of all implicit rules.  Also sets the subdir
  5179.    flag for a rule when appropriate.  */
  5180.  
  5181. static void
  5182. count_implicit_rule_limits ()
  5183. {
  5184.   char *name = 0;
  5185.   int namelen = 0;
  5186.   register struct rule *rule, *lastrule;
  5187.   
  5188.   num_pattern_rules = 0;
  5189.   
  5190.   lastrule = pattern_rules;
  5191.   for (rule = lastrule; rule != 0; lastrule = rule, rule = rule->next)
  5192.     {
  5193.       int ndeps = 0;
  5194.       register struct dep *dep;
  5195.       
  5196.       ++num_pattern_rules;
  5197.       
  5198.       for (dep = rule->deps; dep != 0; dep = dep->next)
  5199.     {
  5200.       int len = strlen (dep_name (dep));
  5201. #ifdef atarist
  5202.       char *p = rindex (dep->name, '\\');
  5203. #else
  5204.       char *p = rindex (dep->name, '/');
  5205. #endif
  5206.       char *p2 = p ? index (dep->name, '%') : 0;
  5207.       if (len > max_pattern_dep_length)
  5208.         max_pattern_dep_length = len;
  5209.       ndeps++;
  5210.       if (p != 0 && p2 > p)
  5211.         {
  5212.           if ((p - dep->name) > namelen)
  5213.         {
  5214.           if (name != 0)
  5215.             free (name);
  5216.           namelen = p - dep->name;
  5217.           name = (char *) xmalloc (namelen + 1);
  5218.         }
  5219.           bcopy (dep->name, name, p - dep->name);
  5220.           name[p - dep->name] = '\0';
  5221.           if (dir_file_exists_p (name, "."))
  5222.         rule->subdir = 0;
  5223.           else
  5224.         {
  5225.           struct stat buf;
  5226.           if (stat (name, &buf) < 0
  5227.               || (buf.st_mode & S_IFMT) != S_IFDIR)
  5228.             {
  5229. #ifdef atarist
  5230.               if (*name == '\\')
  5231. #else
  5232.               if (*name == '/')
  5233. #endif
  5234.             {
  5235.               if (rule == pattern_rules)
  5236.                 pattern_rules = rule->next;
  5237.               else
  5238.                 last_pattern_rule->next = rule->next;
  5239.               free (rule->name);
  5240.               free ((char *) rule);
  5241.             }
  5242.               else
  5243.             rule->subdir = 1;
  5244.             }
  5245.           else
  5246.             {
  5247.               dir_load (name);
  5248.               rule->subdir = 0;
  5249.             }
  5250.         }
  5251.         }
  5252.     }
  5253.       if (ndeps > max_pattern_deps)
  5254.     max_pattern_deps = ndeps;
  5255.     }
  5256.   
  5257.   if (name != 0)
  5258.     free (name);
  5259. }
  5260.  
  5261. /* Read a line of text from `stream' into `linebuffer'.
  5262.    Combine continuation lines into one line.
  5263.    Return the number of actual lines read. (> 1 if hacked continuation lines)
  5264.  */
  5265.  
  5266. static long
  5267. readline (linebuffer, stream, filename, lineno)
  5268.      struct linebuffer *linebuffer;
  5269.      FILE *stream;
  5270.      char *filename;
  5271.      long lineno;
  5272. {
  5273.   register int c;
  5274.   char *buffer = linebuffer->buffer;
  5275.   register char *p = linebuffer->buffer;
  5276.   register char *end = p + linebuffer->size;
  5277.   register int backslash = 0;
  5278.   register int command = 0;
  5279.   register long nlines = 0;
  5280.  
  5281.   while (1)
  5282.     {
  5283.       if (p == end)
  5284.     {
  5285.       register long delta = linebuffer->size;
  5286.       end += delta;
  5287.       buffer = (char *) xrealloc (buffer, linebuffer->size += delta);
  5288.       delta = buffer - linebuffer->buffer;
  5289.       p += delta;
  5290.       end += delta;
  5291.       linebuffer->buffer = buffer;
  5292.     }
  5293.       c = getc (stream);
  5294.  
  5295. #ifdef atarist
  5296.       if (c == '\r')
  5297.     c = getc (stream);
  5298. #endif
  5299.  
  5300.       if (c == EOF)
  5301.     break;
  5302.  
  5303.       if (c == '\0')
  5304.     {
  5305.       /* C (and un*x) suck */
  5306.       fatal ("%s:%ld: null character in makefile",
  5307.          filename, lineno + nlines);
  5308.     }
  5309.  
  5310.       if (c == '\n')
  5311.     {
  5312.       if (!backslash)
  5313.         /* Line not continued.  Return what we have so far.  */
  5314.         break;
  5315.  
  5316.       /* Line ends with odd number of backslashes -- continuation!  */
  5317.       /* We leave backslashes before newlines and whitespace
  5318.          after intact for commands.  */
  5319.       if (command < 1)
  5320.         {
  5321.           /* Discard the backslash that means continuation.  */
  5322.           --p;
  5323.           backslash = 0;
  5324.  
  5325.           /* Discard whitespace at start of next line.  */
  5326.           while ((c = getc (stream)) == ' ' || c == '\t')
  5327.         ;
  5328.           if (ungetc (c, stream) == EOF)
  5329.         fatal ("%s:%ld: ungetc failed", filename, lineno + nlines);
  5330.           /* Replace it all with one space.  */
  5331.           c = ' ';
  5332.         }
  5333.       else
  5334.         {
  5335.           /* Eat a leading tab on a continued command line.  */
  5336.           c = getc (stream);
  5337.           if (c == EOF)
  5338.         fatal ("%s:%ld: getc failed", filename, lineno + nlines);
  5339.           else if (c != '\t')
  5340.         if (ungetc (c, stream) == EOF)
  5341.           fatal ("%s:%ld: ungetc failed", filename, lineno + nlines);
  5342.           c = '\n';
  5343.         }
  5344.       nlines++;
  5345.     }
  5346.  
  5347.       if (command < 1)
  5348.     {
  5349.       if (c == ';' || (command == 0 && !backslash && c == '\t'))
  5350.         command = 1;
  5351.       else
  5352.         command = -1;
  5353.     }
  5354.  
  5355.       if (c == '#' && command < 1)
  5356.     {
  5357.       while (1)
  5358.         {
  5359.           c = getc (stream);
  5360.           if (c == EOF)
  5361.         break;
  5362.           if (c == '\n')
  5363.         {
  5364.           ++nlines;
  5365.           if (!backslash)
  5366.             break;
  5367.         }
  5368.           backslash = c == '\\';
  5369.         }
  5370.       backslash = 0;
  5371.       break;
  5372.     }
  5373.  
  5374.       if (c == '\\')
  5375.     backslash = !backslash;
  5376.       else
  5377.     backslash = 0;
  5378.  
  5379.       *p++ = c;
  5380.     }
  5381.  
  5382.   *p = '\0';
  5383.   nlines++;
  5384.   return (nlines);
  5385. }
  5386.  
  5387. static int
  5388. ar_name (name)
  5389.      char *name;
  5390. {
  5391.   char *p = index (name, '('), *end = name + strlen (name) - 1;
  5392.   
  5393.   if (p == 0 || *end != ')')
  5394.     return 0;
  5395.  
  5396.   if (p[1] == '(' && end[-1] == ')')
  5397.     fatal ("attempt to use unsupported feature: `%s'", name);
  5398.  
  5399.   return 1;
  5400. }
  5401.  
  5402. static int
  5403. ar_scan_1 (name, function)
  5404.      char *name;
  5405.      int (*function) ();
  5406. {
  5407.   char *arname;
  5408.   char *memname;
  5409.   char *p;
  5410.   int val;
  5411.  
  5412.   /* This "file" is an archive member */
  5413.   p = index (name, '(');
  5414.   arname = savestring (name, p - name);
  5415.   memname = savestring (p + 1, strlen (p) - 2);
  5416.  
  5417.   val = ar_scan (arname, function, memname);
  5418.   free (arname);
  5419.   free (memname);
  5420.   return (val);
  5421. }
  5422.  
  5423. /* ARGSUSED */
  5424. static int
  5425. ar_member_date_1 (desc, name, hdrpos, datapos, size, date, uid, gid, mode, mem)
  5426.      int desc;
  5427.      char *name;
  5428.      int hdrpos, datapos, size, date, uid, gid, mode;
  5429.      char *mem;
  5430. {
  5431.   if (streq (name, mem))
  5432.     return (date);
  5433.   else
  5434.     return (0);
  5435. }
  5436.  
  5437. static int
  5438. ar_member_date (name)
  5439.      char *name;
  5440. {
  5441.   return (ar_scan_1 (name, ar_member_date_1));
  5442. }
  5443.  
  5444. static int
  5445. ar_touch (name)
  5446.      char *name;
  5447. {
  5448.   register char *p, *arname, *memname;
  5449.   register int val;
  5450.  
  5451.   p = index (name, '(');
  5452.   arname = savestring (name, p - name);
  5453.   memname = savestring (p + 1, strlen (p) - 2);
  5454.  
  5455.   val = ar_member_touch (arname, memname);
  5456.   if (val == -2)
  5457.     fatal ("Invalid archive %s", arname);
  5458.   if (val < 0)
  5459.     pfatal_with_name (arname);
  5460.   if (val > 0)
  5461.     error ("touch: No such archive member %s", name);
  5462.  
  5463.   free (arname);
  5464.   free (memname);
  5465.  
  5466.   return (val);
  5467. }
  5468.  
  5469. /* Execute LINE as a command.  Try to avoid forking a shell.
  5470.    This routine handles only ' quoting.  Starting quotes may be
  5471.    escaped with a backslash.  If any of the characters ;"*?[]&|<>(){}=
  5472.    is seen, or any of the builtin commands listed in sh_cmds[]
  5473.    is the first word of a line, the shell is used.  */
  5474.  
  5475. static int
  5476. execute_command_line (line)
  5477.      char *line;
  5478. {
  5479.   static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
  5480.                  "logout", "set", "umask", "wait", "while", "for",
  5481.                  "case", "if", ":", ".", "break", "continue",
  5482.                  "export", "read", "readonly", "shift", "times",
  5483.                  "trap", "switch", 0 };
  5484.   register int i;
  5485.   register char *p;
  5486.   register char *ap;
  5487.   char *end;
  5488.   int instring;
  5489. #ifndef atarist
  5490.   union wait status;
  5491. #endif
  5492.   int pid;
  5493.   char **new_argv;
  5494.  
  5495.   new_environ ();
  5496.  
  5497.   /* See if it is safe to parse commands internally.  */
  5498. #ifndef atarist        /* this can't possibly work on ST */
  5499.   if (strcmp (shell_macro->value, "/bin/sh"))
  5500.     goto slow;
  5501.   else if (ifs_macro != 0)
  5502.     for (line = ifs_macro->value; *line != '\0'; ++line)
  5503.       if (*line != ' ' && *line != '\t' && *line != '\n')
  5504.     goto slow;
  5505. #endif
  5506.  
  5507.   i = strlen (line) + 1;
  5508.  
  5509.   /* More than 1 arg per character is impossible.  */
  5510.   new_argv = (char **) alloca (i * sizeof (char *));
  5511.  
  5512.   /* All the args can fit in a buffer as big as LINE is.   */
  5513.   ap = new_argv[0] = (char *) alloca (i);
  5514.   end = ap + i;
  5515.  
  5516.   /* I is how many complete arguments have been found.  */
  5517.   i = 0;
  5518.   instring = 0;
  5519.   for (p = line; *p; ++p)
  5520.     {
  5521.       if (ap > end)
  5522.     {
  5523.       fflush (stdout);
  5524.       fflush (stderr);
  5525.       abort ();
  5526.     }
  5527.  
  5528.       if (instring)
  5529.     {
  5530.       /* Inside a string, just copy any char except a closing quote.  */
  5531.       if (*p == '\'')
  5532.         instring = 0;
  5533.       else
  5534.         *ap++ = *p;
  5535.     }
  5536.       else
  5537.     /* Not inside a string.  */
  5538.     switch (*p)
  5539.       {
  5540. #ifndef atarist
  5541.       case '\\':
  5542.         if (p[1] && p[1] != '\n')
  5543.           /* Copy and skip the following char.  */
  5544.           *ap++ = *++p;
  5545.         break;
  5546. #endif
  5547.  
  5548.       case '\'':
  5549.         instring = 1;
  5550.         break;
  5551.  
  5552.       case ';':
  5553.       case '"':
  5554.       case '*':
  5555.       case '?':
  5556.       case '[':
  5557.       case ']':
  5558.       case '$':
  5559.       case '<':
  5560.       case '>':
  5561.       case '|':
  5562.       case '&':
  5563.       case '=':
  5564.       case '~':
  5565.       case '`':
  5566.       case '(':
  5567.       case ')':
  5568.       case '{':
  5569.       case '}':
  5570.         goto slow;
  5571.  
  5572.       case '\n':
  5573.       case ' ':
  5574.       case '\t':
  5575.         /* We have the end of an argument.
  5576.            Terminate the text of the argument.  */
  5577.         *ap++ = '\0';
  5578.         new_argv[++i] = ap;
  5579.         /* If this argument is the command name,
  5580.            see if it is a built-in shell command.
  5581.            If so, have the shell handle it.  */
  5582.         if (i == 1)
  5583.           {
  5584.         register int j;
  5585.         for (j = 0; sh_cmds[j] != 0; ++j)
  5586.           if (streq (sh_cmds[j], new_argv[0]))
  5587.             goto slow;
  5588.           }
  5589.         /* Ignore multiple whitespace.  */
  5590.         while (*p == ' ' || *p == '\t')
  5591.           ++p;
  5592.         /* Next iteration should examine the first nonwhite char.  */
  5593.         --p;
  5594.         break;
  5595.  
  5596.       case '#':
  5597.         /* # starts a comment, at beginning of word.  */
  5598.         if (p == line || p[-1] == ' ' || p[-1] == '\t')
  5599.           goto endloop;
  5600.  
  5601.         /* Drops in */
  5602.       default:
  5603.         *ap++ = *p;
  5604.         break;
  5605.       }
  5606.     }
  5607.  
  5608.  endloop:
  5609.  
  5610.   /* Terminate the last argument and the argument list.  */
  5611.  
  5612.   *ap = '\0';
  5613.   if (new_argv[i][0] != '\0')
  5614.     ++i;
  5615.   new_argv[i] = 0;
  5616.  
  5617.   if (new_argv[0] == 0)
  5618.     /* Line was empty */
  5619.     return 0;
  5620.  
  5621.   line = new_argv[0];
  5622.   
  5623.   if (0)
  5624.     {
  5625.     slow:;
  5626. #ifndef atarist
  5627.       new_argv = (char **) alloca (4 * sizeof (char *));
  5628.       ap = rindex (shell_macro->value, '/');
  5629.       new_argv[0] = ap == 0 ? shell_macro->value : ap + 1;
  5630.       new_argv[1] = "-c";
  5631.       new_argv[2] = line;
  5632.       new_argv[3] = 0;
  5633.       line = shell_macro->value;
  5634. #else
  5635. /* gulam has bugs such that it sometimes loses horribly to ask it to
  5636.    execute commands.  Unfortunately, there's no help for it, until such
  5637.    time as gulam gets fixed (at which time we can just drop the whole
  5638.    thing and always use gulam) or I fix the startup code to deal with
  5639.    handling its own redirections, in which case we never need use gulam. */
  5640.     {
  5641.     int result;
  5642. /*    fprintf(stderr, "gulam('%s')", line); */
  5643.     result = gulam(line);
  5644. /*    fprintf(stderr, "->%d\n");    */
  5645. /* Sigh.  Unfortunately, gulam also returns gubbish sometimes.  
  5646.    Why is this so hard??? */
  5647.     if (result > 1000)        /* ... a nice arbitrary value */
  5648.         result = 0;
  5649.     return(result);
  5650.     }
  5651. #endif
  5652.     }
  5653.   
  5654.   /* Run the command.  */
  5655.  
  5656. #ifndef atarist
  5657.  
  5658.   pid = vfork ();
  5659.   if (pid == 0)
  5660.     {
  5661.       execvp (line, new_argv);
  5662.       perror_with_name ("execvp: ", line);
  5663.       _exit (127);
  5664.     }
  5665.  
  5666.   if (pid < 0)
  5667.     return (127);
  5668.  
  5669.   /* Wait for termination and report the results.  */
  5670.  
  5671.   while (1)
  5672.     {
  5673.       int wpid;
  5674.       wpid = wait (&status);
  5675.       if (wpid < 0)
  5676.     return (127);
  5677.       else if (wpid != pid)
  5678.     continue;
  5679.       else if (WIFEXITED (status))
  5680.     return (status.w_retcode);
  5681.       else if (WIFSIGNALED (status))
  5682.     {
  5683.       int s;
  5684.       struct stat st;
  5685.  
  5686.       /* Delete the output file that the command was supposed to make.  */
  5687.  
  5688.       if (signal_delete_file
  5689.           && stat (signal_delete_file, &st) >= 0
  5690.           && (st.st_mode & S_IFMT) != S_IFDIR
  5691.           && st.st_mtime != signal_delete_mtime)
  5692.         {
  5693.           fprintf (stderr, "\n%s: Deleting file %s\n",
  5694.                program, signal_delete_file);
  5695.           fflush (stderr);
  5696.           if (unlink (signal_delete_file) < 0)
  5697.         perror_with_name ("unlink: ", signal_delete_file);
  5698.         }
  5699.  
  5700.       /* Treat this as failure.  */
  5701.  
  5702.       s = status.w_termsig | SIGNAL_STATUS;
  5703.       if (status.w_coredump)
  5704.         s |= SIGNAL_COREDUMP;
  5705.       return s;
  5706.     }
  5707.     }
  5708.  
  5709. #else
  5710. /* atari code here... */
  5711.   {
  5712.     return(gspawnv(line, new_argv));
  5713.   }
  5714. #endif
  5715.  
  5716. }
  5717.  
  5718. /* New_environ () sets environ with a new environment for child
  5719.    processes.  The storage is freed at the next call to this routine.
  5720.    The child's MAKELEVEL variable is incremented.  */
  5721.  
  5722. static void
  5723. new_environ ()
  5724. {
  5725.   extern char **environ;
  5726.   register int macro_count, i, mcnt;
  5727.   register struct macro *m;
  5728.  
  5729.   static int free_env = 0;
  5730.  
  5731.   if (free_env)
  5732.     {
  5733.       for (i = 0; environ[i] != 0; ++i)
  5734.     free (environ[i]);
  5735.       free ((char *) environ);
  5736.     }
  5737.  
  5738. #define    identifier_char(c) \
  5739.   (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') \
  5740.    || ((c) >= '0' && (c) <= '9') || (c) == '_')
  5741.  
  5742.   macro_count = 0;
  5743.   for (i = 0; i < MACRO_BUCKETS; ++i)
  5744.     for (m = macros[i]; m != 0; m = m->next)
  5745.       {
  5746.     register char *p;
  5747.     for (p = m->name; *p; ++p)
  5748.       if (!identifier_char (*p))
  5749.         break;
  5750.     if (*p == 0)
  5751.       ++macro_count;
  5752.       }
  5753.  
  5754.   environ = (char **) xmalloc ((macro_count + 2) * sizeof (char *));
  5755.  
  5756.   mcnt = 0;
  5757.   for (i = 0; i < MACRO_BUCKETS; ++i)
  5758.     for (m = macros[i]; m != 0; m = m->next)
  5759.       {
  5760.     register char *p;
  5761.  
  5762.     for (p = m->name; *p; ++p)
  5763.       if (!identifier_char (*p))
  5764.         break;
  5765.     if (*p == '\0')
  5766.       {
  5767.         /* 663 mod MACRO_BUCKETS is "MAKELEVEL"s hash bucket number.  */
  5768.         if (i != (663 % MACRO_BUCKETS) || strcmp ("MAKELEVEL", m->name))
  5769.           {
  5770.         environ[mcnt] = xmalloc (strlen (m->name)
  5771.                      + strlen (m->value) + 2);
  5772.         sprintf (environ[mcnt], "%s=%s", m->name, m->value);
  5773.           }
  5774.         ++mcnt;
  5775.       }
  5776.       }
  5777.  
  5778.   environ[mcnt] = xmalloc (50);
  5779.   sprintf (environ[mcnt], "MAKELEVEL=%d", makelevel + 1);
  5780.  
  5781.   environ[mcnt + 1] = 0;
  5782.  
  5783.   free_env = 1;
  5784.  
  5785.   return;
  5786. }
  5787.  
  5788. /* Print N spaces.  */
  5789.  
  5790. static void
  5791. print_spaces (n)
  5792.      register int n;
  5793. {
  5794.   while (n-- > 0)
  5795.     putchar (' ');
  5796. }
  5797.  
  5798. /* Return the mtime of a file, given a struct file.
  5799.    Caches the time in the struct file to avoid excess stat calls.
  5800.    If the file is not found, VPATH searching and replacement
  5801.    is done.  If that fails, a library (-lLIBNAME) is tried but
  5802.    the library's actual name (/lib/libLIBNAME.a, etc.) is not
  5803.    substituted in.  */
  5804.  
  5805. static long
  5806. f_mtime (file)
  5807.      register struct file *file;
  5808. {
  5809.   register long mtime;
  5810.  
  5811.   if (file->last_mtime != 0L)
  5812.     return (file->last_mtime);
  5813.  
  5814.   /* File's mtime is not known; must get it now from system.  */
  5815.  
  5816.   mtime = name_mtime (file->name);
  5817.  
  5818.   if (mtime == -1L)
  5819.     {
  5820.       /* If the stat failed, search VPATH.  */
  5821.       if (vpath_search (&(file->name), (char *) 0, 0))
  5822.     mtime = name_mtime (file->name);
  5823.       else
  5824.     /* Last resort, is it a library (-lxxx)?  */
  5825.     if (file->name[0] == '-' && file->name[1] == 'l')
  5826.       mtime = library_file_mtime (&file->name[2]);
  5827.     }
  5828.  
  5829.   /* Store the mtime into all the entries for this file.  */
  5830.  
  5831.   while (file)
  5832.     {
  5833.       file->last_mtime = mtime;
  5834.       file = file->prev;
  5835.     }
  5836.   return (mtime);
  5837. }
  5838.  
  5839. static long
  5840. name_mtime (name)
  5841.      register char *name;
  5842. {
  5843.   struct stat st;
  5844.  
  5845.   if (ar_name (name))
  5846.     return (ar_member_date (name));
  5847.  
  5848.   if (stat (name, &st) < 0)
  5849.     return (-1L);
  5850.   return (st.st_mtime);
  5851. }
  5852.  
  5853. /* Read the directory named DIRNAME and enter all of its files
  5854.    in the dir_hash_table.
  5855.  
  5856.    Once a directory's files have been entered,
  5857.    `dir_file_exists_p' may be used to check the existence
  5858.    of any file in that directory.  */
  5859.  
  5860. static void
  5861. dir_load (dirname)
  5862.      char *dirname;
  5863. {
  5864.   register DIR *reading;
  5865.   register struct direct *next;
  5866.   int dirhash;
  5867.   register char *ptr;
  5868.  
  5869.   /* Copy dirname so we can make the hash table entries
  5870.      point at something that will never be freed.  */
  5871.   dirname = savestring (dirname, strlen (dirname));
  5872.  
  5873.   /* Compute hash code of the dir name.
  5874.      This is the starting point for hashing each file name.  */
  5875.  
  5876.   dirhash = 0;
  5877.   ptr = dirname;
  5878.   while (*ptr)
  5879.     {
  5880. #ifdef case_insensitive
  5881.       dirhash += char_upcase(*ptr++);
  5882. #else
  5883.       dirhash += *ptr++;
  5884. #endif
  5885.       dirhash = (dirhash << 7) + (dirhash >> 20);
  5886.     }
  5887.  
  5888.   /* Make a hash table entry for this dir name and no filename,
  5889.      to indicate that `dir_load' has been called for this dir.  */
  5890.   {
  5891.     register int hash;
  5892.     register struct dirdata *new;
  5893.  
  5894.     /* Compute hash code of this dir name.  */
  5895.     hash = dirhash;
  5896.     hash &= 0xffffff;
  5897.     hash %= DIR_HASH_SIZE;
  5898.  
  5899.     /* Add an entry to the hash table.  */
  5900.  
  5901.     new = (struct dirdata *) xmalloc (sizeof (struct dirdata));
  5902.     new->next = dir_hash_table[hash];
  5903.     dir_hash_table[hash] = new;
  5904.     new->dir = dirname;
  5905.     new->name = "";
  5906.     new->impossible = 0;
  5907.   }
  5908.  
  5909.   /* Open the directory and check for errors.  */
  5910. #ifdef atarist
  5911.   {
  5912.     char buf[80];
  5913.  
  5914.     dir_unalias(dirname, buf);
  5915.     reading = opendir(buf);
  5916.   }
  5917. #else
  5918.   reading = opendir (dirname);
  5919. #endif
  5920.   if (reading == 0)
  5921.     return;
  5922.  
  5923.   /* Read the directory entries, and insert the subfiles
  5924.      into the `files' table.  */
  5925.  
  5926.   while (next = readdir (reading))
  5927.     {
  5928.       register int hash;
  5929.       register struct dirdata *new;
  5930.  
  5931. #ifdef atarist
  5932.     string_downcase (next->d_name);
  5933. #endif
  5934.       /* Compute hash code of this file name and dir name.  */
  5935.       hash = dirhash;
  5936.       ptr = next->d_name;
  5937.       while (*ptr)
  5938.     {
  5939. #ifdef case_insensitive
  5940.       hash += char_upcase(*ptr++);
  5941. #else
  5942.       hash += *ptr++;
  5943. #endif
  5944.       hash = (hash << 7) + (hash >> 20);
  5945.     }
  5946.  
  5947.       hash &= 0xffffff;
  5948.       hash %= DIR_HASH_SIZE;
  5949.  
  5950.       /* Add an entry to the hash table.  */
  5951.  
  5952.       new = (struct dirdata *) xmalloc (sizeof (struct dirdata));
  5953.       new->next = dir_hash_table[hash];
  5954.       dir_hash_table[hash] = new;
  5955.       new->dir = dirname;
  5956.       new->name = savestring (next->d_name, strlen (next->d_name));
  5957.       new->impossible = 0;
  5958.     }
  5959.  
  5960.   closedir (reading);
  5961. }
  5962.  
  5963. /* Return 1 if the file named NAME exists.
  5964.    This could work simply by using `access' or
  5965.    by calling `name_mtime', but those ways are too slow.
  5966.    Instead, the first inquiry about any particular directory
  5967.    records the entire contents of that directory in `dir_hash_table'
  5968.    and all inquiries work by checking the table.  */
  5969.  
  5970. static int
  5971. file_exists_p (name)
  5972.      register char *name;
  5973. {
  5974.   char *dirend;
  5975.   char *dirname;
  5976.  
  5977.   if (ar_name (name))
  5978.     return (ar_member_date (name) > 0);
  5979.  
  5980. #ifdef atarist
  5981.   dirend = (char *) rindex (name, '\\');
  5982. #else
  5983.   dirend = (char *) rindex (name, '/');
  5984. #endif
  5985.   if (dirend == 0)
  5986.     return dir_file_exists_p (".", name);
  5987.  
  5988.   dirname = (char *) alloca (dirend - name + 1);
  5989.   bcopy (name, dirname, dirend - name);
  5990.   dirname[dirend - name] = '\0';
  5991.   if (!dir_file_exists_p (dirname, ""))
  5992.     dir_load (dirname);
  5993.   return dir_file_exists_p (dirname, dirend + 1);
  5994. }
  5995.  
  5996. char *dir_name ();
  5997.  
  5998. /* Marks FILENAME as `impossible' for `file_impossible_p'.
  5999.    This means an attempt has been made to search for FILENAME
  6000.    as an intermediate file, and it has failed.  */
  6001.  
  6002. static void
  6003. file_impossible (filename)
  6004.      char *filename;
  6005. {
  6006.   register char *name = filename;
  6007.   register int hash = 0;
  6008.   char *dirend;
  6009.   register struct dirdata *new;
  6010.  
  6011. #ifdef atarist
  6012.   dirend = (char *) rindex (name, '\\');
  6013. #else
  6014.   dirend = (char *) rindex (name, '/');
  6015. #endif
  6016.  
  6017.   while (dirend ? name < dirend : *name)
  6018.     {
  6019. #ifdef case_insensitive
  6020.       hash += char_upcase(*name++);
  6021. #else
  6022.       hash += *name++;
  6023. #endif
  6024.       hash = (hash << 7) + (hash >> 20);
  6025.     }
  6026.  
  6027.   if (dirend != 0)
  6028.     for (name = ++dirend; *name; ++name)
  6029.       {
  6030. #ifdef case_insensitive
  6031.     hash += char_upcase(*name);
  6032. #else
  6033.     hash += *name;
  6034. #endif
  6035.     hash = (hash << 7) + (hash >> 20);
  6036.       }
  6037.  
  6038.   hash &= 0xffffff;
  6039.   hash %= DIR_HASH_SIZE;
  6040.  
  6041.   new = (struct dirdata *) xmalloc (sizeof (struct dirdata));
  6042.   if (dirend != 0)
  6043.     {
  6044.       --dirend;
  6045.       *dirend = '\0';
  6046.       new->dir = dir_name (filename);
  6047. #ifdef atarist
  6048.       *dirend = '\\';
  6049. #else
  6050.       *dirend = '/';
  6051. #endif
  6052.       ++dirend;
  6053.       new->name = savestring (dirend, strlen (dirend));
  6054.     }
  6055.   else
  6056.     {
  6057.       new->dir = dir_name (".");
  6058.       new->name = savestring (filename, strlen (filename));
  6059.     }
  6060.   new->impossible = 1;
  6061.  
  6062.   /* Now put this entry in the table.  */
  6063.  
  6064.   new->next = dir_hash_table[hash];
  6065.   dir_hash_table[hash] = new;
  6066. }
  6067.  
  6068. /* Returns 1 if FILENAME has been marked impossible.  */
  6069.  
  6070. static int
  6071. file_impossible_p (filename)
  6072.      char *filename;
  6073. {
  6074.   register char *name = filename;
  6075.   register int hash = 0;
  6076.   char *dirend;
  6077.   register struct dirdata *next;
  6078.  
  6079. #ifdef atarist
  6080.   dirend = (char *) rindex (name, '\\');
  6081. #else
  6082.   dirend = (char *) rindex (name, '/');
  6083. #endif
  6084.  
  6085.   while (dirend ? name < dirend : *name)
  6086.     {
  6087. #ifdef case_insensitive
  6088.       hash += char_upcase(*name++);
  6089. #else
  6090.       hash += *name++;
  6091. #endif
  6092.       hash = (hash << 7) + (hash >> 20);
  6093.     }
  6094.  
  6095.   if (dirend != 0)
  6096.     for (name = ++dirend; *name; ++name)
  6097.       {
  6098. #ifdef case_insensitive
  6099.     hash += char_upcase(*name);
  6100. #else
  6101.     hash += *name;
  6102. #endif
  6103.     hash = (hash << 7) + (hash >> 20);
  6104.       }
  6105.  
  6106.   hash &= 0xffffff;
  6107.   hash %= DIR_HASH_SIZE;
  6108.  
  6109.   for (next = dir_hash_table[hash]; next != 0; next = next->next)
  6110.     if (dirend != 0)
  6111.       {
  6112.     if (streq (next->name, dirend)
  6113.         && !strncmp (next->dir, filename, dirend - filename - 1))
  6114.       return (next->impossible);
  6115.       }
  6116.     else if (next->dir[0] == '.' && next->dir[1] == '\0'
  6117.              && streq (filename, next->name))
  6118.       return (next->impossible);
  6119.  
  6120.   return (0);
  6121. }
  6122.  
  6123. /* Return 1 if the name FILENAME in directory DIRNAME
  6124.    is entered in the dir hash table.
  6125.    FILENAME must contain no slashes.
  6126.  
  6127.    If the directory has been loaded and the value is 0,
  6128.    then the file did not exist.
  6129.  
  6130.    To see if a directory is described by the table,
  6131.    call with "." for FILENAME.  */
  6132.  
  6133. static int
  6134. dir_file_exists_p (dirname, filename)
  6135.      register char *dirname;
  6136.      register char *filename;
  6137. {
  6138.   register int hash;
  6139.   register char *ptr;
  6140.   register struct dirdata *next;
  6141.  
  6142.   hash = 0;
  6143.   ptr = dirname;
  6144.   while (*ptr)
  6145.     {
  6146. #ifdef case_insensitive
  6147.       hash += char_upcase(*ptr++);
  6148. #else
  6149.       hash += *ptr++;
  6150. #endif
  6151.       hash = (hash << 7) + (hash >> 20);
  6152.     }
  6153.   ptr = filename;
  6154.   while (*ptr)
  6155.     {
  6156. #ifdef case_insensitive
  6157.       hash += char_upcase(*ptr++);
  6158. #else
  6159.       hash += *ptr++;
  6160. #endif
  6161.       hash = (hash << 7) + (hash >> 20);
  6162.     }
  6163.  
  6164.   hash &= 0xffffff;
  6165.   hash %= DIR_HASH_SIZE;
  6166.  
  6167.   for (next = dir_hash_table[hash]; next != 0; next = next->next)
  6168.     if (streq (next->name, filename) && streq (next->dir, dirname))
  6169.       return !next->impossible;
  6170.   return 0;
  6171. }
  6172.  
  6173. /* Return the already allocated name in the directory hash table
  6174.    that matches DIR.  The lookup should be fast and never fail
  6175.    because this routine is called after a dir_load () or
  6176.    dir_file_exists_p () call.  */
  6177.  
  6178. static char *
  6179. dir_name (dir)
  6180.      char *dir;
  6181. {
  6182.   register int hash;
  6183.   register char *ptr;
  6184.   register struct dirdata *next;
  6185.  
  6186.   hash = 0;
  6187.   ptr = dir;
  6188.   while (*ptr)
  6189.     {
  6190. #ifdef case_insensitive
  6191.       hash += char_upcase(*ptr++);
  6192. #else
  6193.       hash += *ptr++;
  6194. #endif
  6195.       hash = (hash << 7) + (hash >> 20);
  6196.     }
  6197.  
  6198.   hash &= 0xffffff;
  6199.   hash %= DIR_HASH_SIZE;
  6200.  
  6201.   for (next = dir_hash_table[hash]; next != 0; next = next->next)
  6202.     if (streq (next->dir, dir))
  6203.       return (next->dir);
  6204.  
  6205.   /* "Things are getting strange.  Perhaps you'd better quit --More--"  */
  6206.   fflush (stdout);
  6207.   fflush (stderr);
  6208.   abort ();
  6209.   return (0);
  6210. }
  6211.  
  6212. int selective_vpath_search ();
  6213.  
  6214. /* Reverse the chain of selective VPATH lists so they
  6215.    will be searched in the order given in the makefiles
  6216.    and construct the list from the VPATH macro.  */
  6217.  
  6218. static void
  6219. build_vpath_lists ()
  6220. {
  6221.   register struct vpath *new = 0;
  6222.   register struct vpath *old, *nexto;
  6223.   register struct macro *m;
  6224.  
  6225.   /* Reverse the chain.  */
  6226.   for (old = vpaths; old != 0; old = nexto)
  6227.     {
  6228.       nexto = old->next;
  6229.       old->next = new;
  6230.       new = old;
  6231.     }
  6232.  
  6233.   vpaths = new;
  6234.  
  6235.   /* If there is a VPATH macro with a nonnull value,
  6236.      construct the general VPATH list from it.  */
  6237.   m = lookup_macro ("VPATH", 5);
  6238.   if (m != 0 && *m->value != '\0')
  6239.     {
  6240.       general_vpath = construct_vpath_list ("%", m->value);
  6241.       /* It was just put into the linked list,
  6242.      but we don't want it there, so we must remove it.  */
  6243.       if (general_vpath)
  6244.         vpaths = general_vpath->next;
  6245.     }
  6246. }
  6247.  
  6248.  
  6249. /* Construct the VPATH listing for the pattern and searchpath given.
  6250.  
  6251.    This function is called to generate selective VPATH lists and also for
  6252.    the general VPATH list (which is in fact just a selective VPATH that
  6253.    is applied to everything).  The returned pointer is either put in the
  6254.    linked list of all selective VPATH lists or in the GENERAL_VPATH
  6255.    variable.
  6256.  
  6257.    If SEARCHPATH is nil, remove all previous listings with the same
  6258.    pattern.  If PATTERN is nil, remove all VPATH listings.
  6259.    Existing and readable directories that are not "." given in the
  6260.    searchpath separated by colons are loaded into the directory hash
  6261.    table if they are not there already and put in the VPATH searchpath
  6262.    for the given pattern with trailing slashes stripped off if present
  6263.    (and if the directory is not the root, "/").
  6264.    The length of the longest entry in the list is put in the structure as well.
  6265.    The address of an malloc'd structure containing the result is returned.  */
  6266.  
  6267. static struct vpath *
  6268. construct_vpath_list (pattern, dirpath)
  6269.      char *pattern, *dirpath;
  6270. {
  6271.   register int elem;
  6272.   register char *p;
  6273.   register char **vpath;
  6274.   register int maxvpath;
  6275.   int maxelem;
  6276.  
  6277.  
  6278.   if (dirpath == 0)
  6279.     {
  6280.       /* Remove matching listings.  */
  6281.       register struct vpath *path, *lastpath;
  6282.  
  6283.       lastpath = vpaths;
  6284.       for (path = vpaths; path != 0; lastpath = path, path = path->next)
  6285.     if (pattern == 0 || streq (pattern, path->pattern))
  6286.       {
  6287.         /* Remove it from the linked list.  */
  6288.         if (lastpath == vpaths)
  6289.           vpaths = path->next;
  6290.         else
  6291.           lastpath->next = path->next;
  6292.  
  6293.         /* Free its unused storage.  */
  6294.         free ((char *) path->searchpath);
  6295.         free ((char *) path);
  6296.       }
  6297.     }
  6298.  
  6299.   /* Skip over any initial colons.  */
  6300.   p = dirpath;
  6301.   while (*p == ':')
  6302.     ++p;
  6303.  
  6304.   /* Figure out the maximum number of VPATH entries and
  6305.      put it in MAXELEM.  We start with 2, one before the
  6306.      first colon and one nil, the list terminator and
  6307.      increment our estimated number for each colon we find.  */
  6308.   maxelem = 2;
  6309.   while (*p)
  6310.     if (*p++ == ':')
  6311.       ++maxelem;
  6312.  
  6313.   vpath = (char **) xmalloc (maxelem * sizeof (char *));
  6314.   maxvpath = 0;
  6315.  
  6316.   elem = 0;
  6317.   p = dirpath;
  6318.   while (*p)
  6319.     {
  6320.       char *v;
  6321.       int len;
  6322.  
  6323.       /* Find the next entry.  */
  6324.       while (*p && *p == ':')
  6325.     ++p;
  6326.       if (*p == '\0')
  6327.     break;
  6328.  
  6329.       /* Find the end of this entry.  */
  6330.       v = p;
  6331.       while (*p && *p != ':')
  6332.     ++p;
  6333.  
  6334.       len = p - v;
  6335.       /* Make sure there's no trailing slash,
  6336.      but still allow "/" as a directory.  */
  6337. #ifdef atarist
  6338.       if (len > 1 && p[-1] == '\\')
  6339. #else
  6340.       if (len > 1 && p[-1] == '/')
  6341. #endif
  6342.     --len;
  6343.  
  6344.       if (len == 1 && *v == '.')
  6345.     continue;
  6346.  
  6347.       v = savestring (v, len);
  6348.       if (dir_file_exists_p (v, "."))
  6349.     {
  6350.       /* The directory is already in the directory hash table.  */
  6351.       vpath[elem] = dir_name (v);
  6352.       maxvpath = max (maxvpath, len);
  6353.       free (v);
  6354.       ++elem;
  6355.     }
  6356.       else
  6357.     {
  6358.       struct stat st;
  6359.       if (stat (v, &st) < 0 || (st.st_mode & S_IFMT) != S_IFDIR)
  6360.         /* Doesn't exist or isn't a directory.  */
  6361.         free (v);
  6362.       else
  6363.         {
  6364.           /* Exists and is a directory, so put it in the directory
  6365.          hash table and the VPATH list.  */
  6366.           dir_load (v);
  6367.           vpath[elem] = dir_name (v);
  6368.           maxvpath = max (maxvpath, len);
  6369.           free (v);
  6370.           ++elem;
  6371.         }
  6372.     }
  6373.     }
  6374.  
  6375.   if (elem > 0)
  6376.     {
  6377.       struct vpath *path;
  6378.       /* ELEM is now incremented one element past the last
  6379.      entry, to where the nil-pointer terminator goes.
  6380.      Usually this is maxelem - 1.  If not, shrink vpath down.  */
  6381.       if (elem < (maxelem - 1))
  6382.     vpath = (char **) xrealloc (vpath, (elem + 1) * sizeof (char *));
  6383.  
  6384.       /* Put the nil-pointer terminator on the end of the VPATH list.  */
  6385.       vpath[elem] = 0;
  6386.  
  6387.       /* Construct the vpath structure and put it into the linked list.  */
  6388.       path = (struct vpath *) xmalloc (sizeof (struct vpath));
  6389.       path->searchpath = vpath;
  6390.       path->maxlen = maxvpath;
  6391.       path->next = vpaths;
  6392.       vpaths = path;
  6393.  
  6394.       /* Set up the members.  */
  6395.       path->patlen = strlen (pattern);
  6396.       path->pattern = savestring (pattern, path->patlen);
  6397.       p = index (path->pattern, '%');
  6398.       path->patsuffix = p == 0 ? 0 : p + 1;
  6399.  
  6400.       return path;
  6401.     }
  6402.   else
  6403.     {
  6404.       /* There were no entries, so free whatever space we allocated.  */
  6405.       free ((char *) vpath);
  6406.       return 0;
  6407.     }
  6408. }
  6409.  
  6410.  
  6411. /* Search the VPATH list whose pattern matches *FILE for a directory
  6412.    where the name pointed to by FILE exists.  If it is found, the pointer
  6413.    in FILE is set to the newly malloc'd name of the existing file and
  6414.    we return 1.  Otherwise we return 0.
  6415.  
  6416.    If DIRPREFIX is non-null, it specifies a directory prefix to be
  6417.    prepended to the name with VPATH directory and DPLEN
  6418.    is the length of this prefix.  */
  6419.  
  6420. static int
  6421. vpath_search (file, dirprefix, dplen)
  6422.      char **file;
  6423.      char *dirprefix;
  6424.      int dplen;
  6425. {
  6426.   register struct vpath *v;
  6427.   register int flen;
  6428.  
  6429.   /* If there are no VPATH entries or FILENAME starts at the root,
  6430.      there is nothing we can do.  */
  6431.  
  6432. #ifdef atarist
  6433.   if (**file == '\\' || (vpaths == 0 && general_vpath == 0))
  6434. #else
  6435.   if (**file == '/' || (vpaths == 0 && general_vpath == 0))
  6436. #endif
  6437.     return 0;
  6438.  
  6439.   flen = strlen (*file);
  6440.  
  6441.   for (v = vpaths; v != 0; v = v->next)
  6442.     {
  6443.       register int i;
  6444.  
  6445.       if (v->patsuffix == 0)
  6446.     {
  6447.       if (*v->pattern != **file || !streq (v->pattern, *file))
  6448.         continue;
  6449.       else if (selective_vpath_search (v, file, dirprefix, dplen))
  6450.         return 1;
  6451.       else
  6452.         continue;
  6453.     }
  6454.  
  6455.       i = (v->patsuffix - v->pattern) - 1;
  6456.       if (i > 0 && i <= flen && (**file != *v->pattern
  6457.                                  || strncmp (*file + 1, v->pattern + 1, i - 1)))
  6458.     continue;
  6459.  
  6460.       i = v->patlen - i - 1;
  6461.       if (i > 0 && strcmp (v->patsuffix, *file + flen - i))
  6462.     continue;
  6463.  
  6464.       if (selective_vpath_search (v, file, dirprefix, dplen))
  6465.     return 1;
  6466.     }
  6467.  
  6468.   if (general_vpath != 0)
  6469.     return selective_vpath_search (general_vpath, file, dirprefix, dplen);
  6470.   else
  6471.     return 0;
  6472. }
  6473.  
  6474.  
  6475. /* Search the given VPATH list for a directory where the name pointed
  6476.    to by FILE exists.  If it is found, the pointer in FILE
  6477.    is set to the newly malloc'd name of the existing file and we return 1.
  6478.    Otherwise we return 0.
  6479.  
  6480.    If DIRPREFIX is non-null, it specifies a directory prefix to be
  6481.    prepended to the name with VPATH directory and DPLEN
  6482.    is the length of this prefix.  */
  6483.  
  6484. static int
  6485. selective_vpath_search (path, file, dirprefix, dplen)
  6486.      struct vpath *path;
  6487.      char **file;
  6488.      char *dirprefix;
  6489.      int dplen;
  6490. {
  6491.   char *name, *n;
  6492.   char *filename;
  6493.   register char **vpath = path->searchpath;
  6494.   int maxvpath = path->maxlen;
  6495.   register int i;
  6496.   int flen, vlen;
  6497.   int name_dplen;
  6498.   int exists;
  6499.  
  6500.   flen = strlen (*file);
  6501.  
  6502.   /* Split *FILE into a directory prefix and a name-within-directory.
  6503.      NAME_DPLEN gets the length of the prefix; FILENAME gets the
  6504.      pointer to the name-within-directory and FLEN is its length.  */
  6505.  
  6506. #ifdef atarist
  6507.   n = rindex (*file, '\\');
  6508. #else
  6509.   n = rindex (*file, '/');
  6510. #endif
  6511.   name_dplen = n ? n - *file : 0;
  6512.   filename = name_dplen > 0 ? n + 1 : *file;
  6513.   if (name_dplen > 0)
  6514.     flen -= name_dplen + 1;
  6515.  
  6516.   /* Allocate enough space for the directory prefix, the biggest
  6517.      VPATH entry, a slash, the directory prefix that came with *FILE,
  6518.      another slash (although this one may not always be necessary),
  6519.      the filename, and a null terminator.  */
  6520.   name = (char *) alloca (dplen + maxvpath + 1 + name_dplen + 1 + flen + 1);
  6521.  
  6522.   /* Try each VPATH entry.  */
  6523.   for (i = 0; vpath[i] != 0; ++i)
  6524.     {
  6525.       /* Start with the directory prefix, if any,
  6526.      unless this VPATH element is absolute.  */
  6527. #ifdef atarist
  6528.       if (*vpath[i] != '\\' && dirprefix != 0)
  6529. #else
  6530.       if (*vpath[i] != '/' && dirprefix != 0)
  6531. #endif
  6532.     {
  6533.       bcopy (dirprefix, name, dplen);
  6534.       n = name + dplen;
  6535.     }
  6536.       else
  6537.     n = name;
  6538.  
  6539.       /* Put the next VPATH entry into NAME at N and increment N past it.  */
  6540.       vlen = strlen (vpath[i]);
  6541.       bcopy (vpath[i], n, vlen);
  6542.       n += vlen;
  6543.  
  6544.       /* Add the directory prefix already in *FILE.  */
  6545.       if (name_dplen > 0)
  6546.     {
  6547. #ifdef atarist
  6548.       *n++ = '\\';
  6549. #else
  6550.       *n++ = '/';
  6551. #endif
  6552.       bcopy (*file, n, name_dplen);
  6553.       n += name_dplen;
  6554.     }
  6555.  
  6556.       /* Null-terminate the string.
  6557.      Now NAME is the name of the directory to look in.  */
  6558.       *n = '\0';
  6559.  
  6560.       /* Make sure the directory exists and we know its contents.  */
  6561.       if ((dirprefix != 0 || name_dplen > 0) && !dir_file_exists_p (name, "."))
  6562.     {
  6563.       struct stat st;
  6564.       if (stat (name, &st) < 0 || (st.st_mode & S_IFMT) != S_IFDIR)
  6565.         /* Doesn't exist or isn't a directory.  */
  6566.         continue;    /* for I  */
  6567.       else
  6568.         dir_load (name);
  6569.     }
  6570.  
  6571.       /* We know the directory is in the hash table now because either
  6572.          construct_vpath_list or the code just above put it there.
  6573.      Does the file we seek exist in it?  */
  6574.  
  6575.       exists = dir_file_exists_p (name, filename);
  6576.  
  6577.       /* Now add the name-within-directory at the end of NAME.  */
  6578.  
  6579. #ifdef atarist
  6580.       if (n != name && n[-1] != '\\')
  6581.     *n++ = '\\';
  6582. #else
  6583.       if (n != name && n[-1] != '/')
  6584.     *n++ = '/';
  6585. #endif
  6586.       bcopy (filename, n, flen + 1);
  6587.  
  6588.       /* Is the file mentioned in the makefile?
  6589.      That counts as almost existing.  */
  6590.  
  6591.       if (!exists)
  6592.     exists = lookup_file (name) != 0;
  6593.  
  6594.       if (exists)
  6595.     {
  6596.       /* We have found a file.  */
  6597.       /* Store the name we found into *FILE for the caller.  */
  6598.  
  6599.       *file = savestring (name, (n - name) + flen);
  6600.  
  6601.       return 1;
  6602.     }
  6603.     }
  6604.  
  6605.   return 0;
  6606. }
  6607.  
  6608. /* Return the mtime of a library file specified as -lLIBNAME,
  6609.    searching for a suitable library file in the system library directories
  6610.    and the VPATH directories.  */
  6611.  
  6612. static long
  6613. library_file_mtime (lib)
  6614.      char *lib;
  6615. {
  6616.   long mtime;
  6617.   char *name;
  6618.  
  6619. #ifdef atarist
  6620.   if (!dir_file_exists_p ("d:\\gnu\\lib", "."))
  6621.     dir_load ("/usr/lib");
  6622.   if (!dir_file_exists_p ("d:\\lib", "."))
  6623.     dir_load ("/lib");
  6624. #else
  6625.   if (!dir_file_exists_p ("/usr/lib", "."))
  6626.     dir_load ("/usr/lib");
  6627.   if (!dir_file_exists_p ("/lib", "."))
  6628.     dir_load ("/lib");
  6629. #endif
  6630.  
  6631. #ifdef atarist
  6632. /* this stuff is all fucked anyway... */
  6633.   lib = concat ("lib", lib, ".olb");
  6634. #else
  6635.   lib = concat ("lib", lib, ".a");
  6636. #endif
  6637.   name = concat ("/usr/lib/", lib, "");
  6638.   if (dir_file_exists_p ("/usr/lib", lib))
  6639.     mtime = name_mtime (name);
  6640.   else if (dir_file_exists_p ("/lib", lib))
  6641.     mtime = name_mtime (name + 4);
  6642.   else if (vpath_search (&lib, (char *) 0, 0))
  6643.     mtime = name_mtime (lib);
  6644.  
  6645.   free (lib);
  6646.   free (name);
  6647.  
  6648.   return (mtime);
  6649. }
  6650.  
  6651. /* Return a newly-allocated string whose contents concatenate those of s1, s2, s3.  */
  6652.  
  6653. static char *
  6654. concat (s1, s2, s3)
  6655.      char *s1, *s2, *s3;
  6656. {
  6657.   register int len1, len2, len3;
  6658.   register char *result;
  6659.  
  6660.   len1 = *s1 ? strlen (s1) : 0;
  6661.   len2 = *s2 ? strlen (s2) : 0;
  6662.   len3 = *s3 ? strlen (s3) : 0;
  6663.  
  6664.   result = xmalloc (len1 + len2 + len3 + 1);
  6665.  
  6666.   if (*s1)
  6667.     bcopy (s1, result, len1);
  6668.   if (*s2)
  6669.     bcopy (s2, result + len1, len2);
  6670.   if (*s3)
  6671.     bcopy (s3, result + len1 + len2, len3);
  6672.   *(result + len1 + len2 + len3) = '\0';
  6673.  
  6674.   return (result);
  6675. }
  6676.  
  6677. /* Print error message and exit.  */
  6678.  
  6679. /* VARARGS1 */
  6680. static void
  6681. fatal (s1, s2, s3, s4, s5)
  6682.      char *s1, *s2, *s3, *s4, *s5;
  6683. {
  6684.   fprintf (stderr, "%s: ", program);
  6685.   fprintf (stderr, s1, s2, s3, s4, s5);
  6686.   fputs (".  Stop.\n", stderr);
  6687.  
  6688.   if (print_directory_flag)
  6689.     log_working_directory (0);
  6690.  
  6691.   exit (1);
  6692. }
  6693.  
  6694. /* Print error message.  `s1' is printf control string, `s2' is arg for it. */
  6695.  
  6696. /* VARARGS1 */
  6697.  
  6698. static void
  6699. error (s1, s2)
  6700.      char *s1, *s2;
  6701. {
  6702.   fprintf (stderr, "%s: ", program);
  6703.   fprintf (stderr, s1, s2);
  6704.   putc ('\n', stderr);
  6705.   fflush (stderr);
  6706. }
  6707.  
  6708. static void
  6709. perror_with_name (str, name)
  6710.      char *str, *name;
  6711. {
  6712.   extern int errno, sys_nerr;
  6713.   extern char *sys_errlist[];
  6714.  
  6715.   fprintf (stderr, "%s: %s%s: ", program, str, name);
  6716. #ifdef atarist
  6717.   if ((errno > sys_nerr) && (errno <= 0))
  6718. #else
  6719.   if (errno < sys_nerr)
  6720. #endif
  6721.     fprintf (stderr, "%s\n", sys_errlist[errno]);
  6722.   else
  6723.     fprintf (stderr, "Unknown error %d\n", errno);
  6724.   fflush (stderr);
  6725. }
  6726.  
  6727. static void
  6728. pfatal_with_name (name)
  6729.      char *name;
  6730. {
  6731.   extern int errno, sys_nerr;
  6732.   extern char *sys_errlist[];
  6733.  
  6734. #ifdef atarist
  6735.   if ((errno > sys_nerr) && (errno <= 0))
  6736. #else
  6737.   if (errno < sys_nerr)
  6738. #endif
  6739.     fprintf (stderr, "%s: %s: %s\n", program, name, sys_errlist[errno]);
  6740.   else
  6741.     fprintf (stderr, "%s: %s: Unknown error %d\n", program, name, errno);
  6742.  
  6743.   exit (1);
  6744. }
  6745.  
  6746.  
  6747. /* Like malloc but get fatal error if memory is exhausted.  */
  6748. extern char *malloc (), *realloc ();
  6749.  
  6750. static char *
  6751. xmalloc (size)
  6752.      unsigned size;
  6753. {
  6754.   char *result = malloc (size);
  6755.   if (result == 0)
  6756.     fatal ("virtual memory exhausted");
  6757.   return (result);
  6758. }
  6759.  
  6760.  
  6761. static char *
  6762. xrealloc (ptr, size)
  6763.      char *ptr;
  6764.      unsigned size;
  6765. {
  6766.   char *result = realloc (ptr, size);
  6767.   if (result == 0)
  6768.     fatal ("virtual memory exhausted");
  6769.   return (result);
  6770. }
  6771.  
  6772. static char *
  6773. savestring (string, length)
  6774.      char *string;
  6775.      int length;
  6776. {
  6777.   register char *out = (char *) xmalloc ((unsigned) length + 1);
  6778.   if (length > 0) bcopy (string, out, length);
  6779.   out[length] = '\0';
  6780.   return (out);
  6781. }
  6782.  
  6783. /* Search string BIG (length BLEN) for an occurrence of
  6784.    string SMALL (length SLEN).  Return a pointer to the
  6785.    beginning of the first occurrence, or return nil if none found.  */
  6786.  
  6787. static char *
  6788. sindex (big, blen, small, slen)
  6789.      char *big, *small;
  6790.      int blen, slen;
  6791. {
  6792.   register int b;
  6793.  
  6794.   if (blen < 1)
  6795.     blen = strlen (big);
  6796.   if (slen < 1)
  6797.     slen = strlen (small);
  6798.  
  6799.   for (b = 0; b < blen; ++b)
  6800.     if (big[b] == *small && !strncmp (&big[b + 1], small + 1, slen - 1))
  6801.       return (&big[b]);
  6802.  
  6803.   return (0);
  6804. }
  6805.  
  6806. /* Limited INDEX:
  6807.    Search through the string STRING, which ends at LIMIT, for the character C.
  6808.    Returns a pointer to the first occurrence, or nil if none is found.
  6809.    Like INDEX except that the string searched ends where specified
  6810.    instead of at the first null.  */
  6811.  
  6812. static char *
  6813. lindex (string, limit, c)
  6814.      register char *string, *limit;
  6815.      char c;
  6816. {
  6817.   while (string != limit)
  6818.     if (*string++ == c)
  6819.       return string - 1;
  6820.  
  6821.   return 0;
  6822. }
  6823.  
  6824. /* Convert old-style suffix rules to pattern rules.
  6825.    All rules for the suffixes on the .SUFFIXES list
  6826.    are converted and added to the chain of pattern rules.  */
  6827.  
  6828. static void
  6829. convert_to_pattern ()
  6830. {
  6831.   register struct dep *d, *d2, *newd;
  6832.   register struct file *f;
  6833.   register struct rule *r;
  6834.   register char *rulename = (char *) alloca (maxsuffix * 2 + 1);
  6835.   register int slen, s2len;
  6836.  
  6837.   for (d = suffix_file->deps; d != 0; d = d->next)
  6838.     {
  6839.       slen = strlen (dep_name (d));
  6840.       r = (struct rule *) xmalloc (sizeof (struct rule));
  6841.       r->name = savestring ("%", 1 + slen);
  6842.       r->patsuffix = r->name + 1;
  6843.       bcopy (dep_name (d), r->patsuffix, slen + 1);
  6844.       r->namelen = strlen (r->name);
  6845.       r->deps = 0;
  6846.       r->cmds = 0;
  6847.       f = d->file;
  6848.       new_pattern_rule (r, 0);
  6849.       if (f->cmds && f->deps == 0)
  6850.     {
  6851.       for (r = pattern_rules; r != 0; r = r->next)
  6852.         if (r->name[1] == '\0' && r->deps != 0 && r->deps->next == 0
  6853.         && r->deps->name[0] == '%'
  6854.         && streq (r->deps->name + 1, dep_name (d)))
  6855.           break;
  6856.       if (r == 0)
  6857.         {
  6858.           /* Record a pattern for this suffix's null-suffix rule.  */
  6859.           r = (struct rule *) xmalloc (sizeof (struct rule));
  6860.           r->cmds = f->cmds;
  6861.           r->recursive = f->recursive;
  6862.           r->name = savestring ("%", 1);
  6863.           r->namelen = 1;
  6864.           r->patsuffix = r->name + 1;
  6865.           r->terminal = 0;
  6866.           newd = (struct dep *) xmalloc (sizeof (struct dep));
  6867.           newd->name = savestring ("%", 1 + slen);
  6868.           bcopy (dep_name (d), newd->name + 1, slen + 1);
  6869.           newd->next = f->deps;
  6870.           r->deps = newd;
  6871.           /* Install this rule.  */
  6872.           new_pattern_rule (r, 0);
  6873.         }
  6874.     }
  6875.  
  6876.       bcopy (dep_name (d), rulename, slen);
  6877.       /* Record a pattern for each of this suffix's
  6878.      two-suffix rules.  */
  6879.       for (d2 = suffix_file->deps; d2; d2 = d2->next)
  6880.     {
  6881.       if (streq (dep_name (d), dep_name (d2)))
  6882.         continue;
  6883.  
  6884.       s2len = strlen (dep_name (d2));
  6885.       bcopy (dep_name (d2), rulename + slen, s2len + 1);
  6886.       f = lookup_file (rulename);
  6887.       if (f == 0 || f->deps != 0)
  6888.         continue;
  6889.  
  6890.       for (r = pattern_rules; r != 0; r = r->next)
  6891.         if (r->deps && r->deps->next == 0
  6892.             && r->name[0] == '%' && streq (r->name + 1, dep_name (d2))
  6893.             && r->deps->name[0] == '%'
  6894.         && streq (r->deps->name + 1, dep_name (d)))
  6895.               break;
  6896.       if (r != 0)
  6897.         continue;
  6898.  
  6899.       r = (struct rule *) xmalloc (sizeof (struct rule));
  6900.       r->cmds = f->cmds;
  6901.       r->recursive = f->recursive;
  6902.       newd = (struct dep *) xmalloc (sizeof (struct dep));
  6903. #ifdef atarist
  6904.       if (s2len == 4 && !strcmp (dep_name (d2), ".olb"))
  6905. #else
  6906.       if (s2len == 2 && !strcmp (dep_name (d2), ".a"))
  6907. #endif
  6908.         {
  6909.           /* A suffix rule `.X.a:' is converted into
  6910.              the pattern rule `(%.o): %.X'.  */
  6911.           r->namelen = 4;
  6912.           r->name = savestring ("(%.o)", 4);
  6913.           r->patsuffix = r->name + 2;
  6914.           newd->name = savestring ("%", 1 + s2len);
  6915.           bcopy (dep_name (d2), newd->name, s2len + 1);
  6916.         }
  6917.       else
  6918.         {
  6919.           r->namelen = 1 + s2len;
  6920.           r->name = savestring ("%", 1 + s2len);
  6921.           r->patsuffix = r->name + 1;
  6922.           bcopy (dep_name (d2), r->patsuffix, s2len + 1);
  6923.           newd->name = savestring ("%", 1 + slen);
  6924.           bcopy (dep_name (d), newd->name + 1, slen + 1);
  6925.         }
  6926.       newd->next = f->deps;
  6927.       r->deps = newd;
  6928.       new_pattern_rule (r, 0);
  6929.     }
  6930.     }
  6931. }
  6932.  
  6933. /* Install the pattern rule RULE (whose fields have been filled in)
  6934.    at the end of the list (so that any rules previously defined
  6935.    will take precedence).  If this rule duplicates a previous one
  6936.    (identical target and dependents), the old one is replaced
  6937.    if OVERRIDE is nonzero, otherwise this new one is thrown out.
  6938.    When an old rule is replaced, the new one is put at the end of the
  6939.    list.  */
  6940.  
  6941. static void
  6942. new_pattern_rule (rule, override)
  6943.      register struct rule *rule;
  6944.      int override;
  6945. {
  6946.   register struct rule *r, *lastrule;
  6947.  
  6948.   rule->subdir = 0;
  6949.   rule->in_use = 0;
  6950.   rule->recursive = 0;
  6951.   rule->terminal = 0;
  6952.  
  6953.   rule->next = 0;
  6954.  
  6955.   /* Search for an identical rule.  */
  6956.   lastrule = pattern_rules;
  6957.   for (r = pattern_rules; r != 0; lastrule = r, r = r->next)
  6958.     if (streq (rule->name, r->name))
  6959.       {
  6960.     register struct dep *d, *d2;
  6961.     for (d = rule->deps, d2 = r->deps; d && d2; d = d->next, d2 = d2->next)
  6962.       if (!streq (dep_name (d), dep_name (d2)))
  6963.         break;
  6964.     if (d == 0 && d2 == 0)
  6965.       {
  6966.         /* All the dependents matched.  */
  6967.         if (override)
  6968.           {
  6969.         /* Remove the old rule.  */
  6970.         if (lastrule == pattern_rules)
  6971.           pattern_rules = r->next;
  6972.         else
  6973.           lastrule->next = r->next;
  6974.         /* Install the new one.  */
  6975.         if (pattern_rules == 0)
  6976.           pattern_rules = rule;
  6977.         else
  6978.           last_pattern_rule->next = rule;
  6979.         last_pattern_rule = rule;
  6980.           }
  6981.         else
  6982.           /* The old rule stays intact.  Destroy the new one.  */
  6983.           r = rule;
  6984.  
  6985.         /* Free all the storage allocated for the rule being
  6986.            destroyed that will not be used elsewhere.  */
  6987.         free (r->name);
  6988.         if (r->deps)
  6989.           free ((char *) r->deps);
  6990.         if (r->cmds)
  6991.           {
  6992.         free (r->cmds->commands);
  6993.         free ((char *) r->cmds);
  6994.           }
  6995.         break;
  6996.       }
  6997.       }
  6998.  
  6999.   if (r == 0)
  7000.     {
  7001.       /* There was no rule to replace.  */
  7002.       if (pattern_rules == 0)
  7003.     pattern_rules = rule;
  7004.       else
  7005.     last_pattern_rule->next = rule;
  7006.       last_pattern_rule = rule;
  7007.     }
  7008. }
  7009.  
  7010. /* Install an implicit pattern rule based on the three text strings
  7011.    in the structure P points to.  These strings come from one of
  7012.    the arrays on the preceding page.
  7013.    TERMINAL specifies what the `terminal' field of the rule should be.  */
  7014.  
  7015. static void
  7016. install_pattern_rule (p, terminal)
  7017.      struct pspec *p;
  7018.      int terminal;
  7019. {
  7020.   struct rule *r;
  7021.   char *ptr;
  7022.   int cmdlen;
  7023.  
  7024.   r = (struct rule *) xmalloc (sizeof (struct rule));
  7025.   r->namelen = strlen (p->target);
  7026.   /* These will all be string literals, but we malloc space for them
  7027.      anyway because somebody might want to free them later.  */
  7028.   r->name = savestring (p->target, r->namelen);
  7029.   r->patsuffix = index (r->name, '%') + 1;
  7030.  
  7031.   r->terminal = terminal;
  7032.   ptr = p->dep;
  7033.   r->deps = (struct dep *) multi_glob (parse_file_seq (&ptr, '\0',
  7034.                                                        sizeof (struct dep)),
  7035.                        sizeof (struct dep));
  7036.   r->cmds = (struct commands *) xmalloc (sizeof (struct commands));
  7037.   r->cmds->filename = 0;
  7038.   r->cmds->lineno = 0;
  7039.   cmdlen = strlen (p->commands);
  7040.   /* These will all be string literals, but we malloc space for them
  7041.      anyway because somebody might want to free them later.  */
  7042.   r->cmds->commands = savestring (p->commands, cmdlen);
  7043.   r->recursive = sindex (p->commands, cmdlen, "$(MAKE)", 7)
  7044.                  || sindex (p->commands, cmdlen, "${MAKE}", 7);
  7045.  
  7046.   new_pattern_rule (r, 0);
  7047. }
  7048.  
  7049. /* Construct the list of include directories from the
  7050.    arguments and the default list.  */
  7051.  
  7052. static void
  7053. construct_include_path (argc, argv)
  7054.      int argc;
  7055.      char **argv;
  7056. {
  7057.   register int i;
  7058.   struct stat stbuf;
  7059.  
  7060.   /* Table to hold the dirs, long enough for the worst case
  7061.      plus a null pointer at the end.  */
  7062.  
  7063.   register char **dirs
  7064.     = (char **) xmalloc ((argc
  7065.               + (sizeof (default_include_directories)
  7066.                  / sizeof (char *)) - 1)
  7067.              * sizeof (char *));
  7068.   /* Number of elements in DIRS currently in use.  */
  7069.   register int count = 0;
  7070.  
  7071.   include_directories = dirs;
  7072.  
  7073.   /* First consider any dirs specified with -I switches.
  7074.      Ignore dirs that don't exist.  */
  7075.  
  7076.   for (i = 0; i < argc; ++i)
  7077.     if (!strcmp (argv[i], "-I"))
  7078.       {
  7079.     ++i;
  7080.     if (argv[i] == 0)
  7081.       fatal ("no directory given after -I switch");
  7082.     if (stat (argv[i], &stbuf) == 0
  7083.         && (stbuf.st_mode & S_IFMT) == S_IFDIR)
  7084.       dirs[count++] = argv[i];
  7085.       }
  7086.     else if (!strcmp (argv[i], "-f") || !strcmp (argv[i], "-o"))
  7087.       ++i;
  7088.  
  7089.   /* Now add at the end the standard default dirs.  */
  7090.  
  7091.   for (i = 0; default_include_directories[i] != 0; ++i)
  7092.     if (stat (default_include_directories[i], &stbuf) == 0
  7093.     && (stbuf.st_mode & S_IFMT) == S_IFDIR)
  7094.       dirs[count++] = default_include_directories[i];
  7095.  
  7096.   dirs[count] = 0;
  7097.  
  7098.   /* Now compute the maximum length of any name in it.  */
  7099.  
  7100.   max_incl_len = 0;
  7101.   for (i = 0; i < count; ++i)
  7102.     {
  7103.       int len = strlen (dirs[i]);
  7104.       /* If dir name is written with a trailing slash, discard it.  */
  7105. #ifdef atarist
  7106.       if (dirs[i][len - 1] == '\\')
  7107. #else
  7108.       if (dirs[i][len - 1] == '/')
  7109. #endif
  7110.     dirs[i] = savestring (dirs[i], len - 1);
  7111.       max_incl_len = max (max_incl_len, len);
  7112.     }
  7113. }
  7114.  
  7115. /* Return the address of the first whitespace or null in the string S.  */
  7116.  
  7117. static char *
  7118. end_of_token (s)
  7119.      char *s;
  7120. {
  7121.   register char *p = s;
  7122.   register int backslash = 0;
  7123.  
  7124.   while (*p && (!backslash && (*p != ' ' && *p != '\t')))
  7125.     {
  7126.       if (*p++ == '\\')
  7127.     {
  7128.       backslash = !backslash;
  7129. #ifdef atarist
  7130.       while (*p == '\\')
  7131. #else
  7132.       while (*p == '/')
  7133. #endif
  7134.         {
  7135.           backslash = !backslash;
  7136.           ++p;
  7137.         }
  7138.     }
  7139.       else
  7140.     backslash = 0;
  7141.     }
  7142.  
  7143.   return p;
  7144. }
  7145.  
  7146. /* Return the address of the first nonwhitespace or null in the string S.  */
  7147.  
  7148. static char *
  7149. next_token (s)
  7150.      char *s;
  7151. {
  7152.   register char *p = s;
  7153.  
  7154.   while (*p == ' ' || *p == '\t') ++p;
  7155.   return p;
  7156. }
  7157.  
  7158. /* Find the next token in PTR; return the address of it,
  7159.    and store the length of the token into *LENGTHPTR.  */
  7160.  
  7161. static char *
  7162. find_next_token (ptr, lengthptr)
  7163.      char **ptr;
  7164.      int *lengthptr;
  7165. {
  7166.   char *p = next_token (*ptr);
  7167.   char *end;
  7168.  
  7169.   if (*p == '\0')
  7170.     return 0;
  7171.  
  7172.   *ptr = end = end_of_token (p);
  7173.   *lengthptr = end - p;
  7174.   return p;
  7175. }
  7176.  
  7177. /* Scan a string and find the whitespace-separated tokens composing it.
  7178.    wstok (S) specifies the string to scan, and returns the address of the
  7179.    first token.  wstok (0) gets the next token.  Repeat wstok (0) until
  7180.    the tokens are exhausted, which is indicated by a value of zero.
  7181.  
  7182.    The token that is returned is made into a null-terminated string
  7183.    by storing a zero at the end of it.  The following call to wstok
  7184.    restores the original contents of that character.  */
  7185.  
  7186. char *wstok_last_token_end;    /* Address of end of last token, now a null */
  7187. char wstok_saved_end_char;    /* Previous contents of that char */
  7188.  
  7189. static char *
  7190. wstok (s)
  7191.      char *s;
  7192. {
  7193.   char *beg;
  7194.   int length;
  7195.  
  7196.   if (s != 0)
  7197.     wstok_last_token_end = s;
  7198.   else
  7199.     *wstok_last_token_end = wstok_saved_end_char;
  7200.  
  7201.   beg = find_next_token (&wstok_last_token_end, &length);
  7202.   wstok_saved_end_char = *wstok_last_token_end;
  7203.   *wstok_last_token_end = '\0';
  7204.  
  7205.   return beg;
  7206. }
  7207.  
  7208. /* Write a message indicating that we've just entered or
  7209.    left (according to ENTERING) the current directory.  */
  7210.  
  7211. static void
  7212. log_working_directory (entering)
  7213.      int entering;
  7214. {
  7215.   char pwdbuf[MAXPATHLEN];
  7216.   char *message = entering ? "Entering" : "Leaving";
  7217.  
  7218.   if (getwd (pwdbuf) == 0)
  7219.     printf ("%s: %s an unknown directory (getwd: %s)\n",
  7220.         program, message, pwdbuf);
  7221.   else
  7222.     printf ("%s: %s directory `%s'\n", program, message, pwdbuf);
  7223. }
  7224.  
  7225. #if 0    /* dummy tags for etags */
  7226. fmt (){}
  7227. formatting (){}
  7228. #endif
  7229.  
  7230. /* Emacs C-mode formatting variables:
  7231.    Local Variables:
  7232.    c-argdecl-indent: 5
  7233.    c-auto-newline: t
  7234.    c-brace-imaginary-offset: 0
  7235.    c-brace-offset: 0
  7236.    c-continued-brace-offset: 0
  7237.    c-continued-statement-offset: 2
  7238.    c-indent-level: 2
  7239.    c-label-offset: -2
  7240.    End:
  7241.  */
  7242.